"use strict";(globalThis.webpackChunk_github_ui_github_ui=globalThis.webpackChunk_github_ui_github_ui||[]).push([["packages_copilot-chat_utils_CopilotChatContext_tsx-packages_safe-html_VerifiedHTML_tsx"],{2635:(e,t,s)=>{s.d(t,{Mj:()=>N,IJ:()=>F,Pk:()=>x,pn:()=>G,A3:()=>H,bP:()=>U,mo:()=>B});var r=s(74848),a=s(21728),i=s(33535),n=s(88431),o=s(96540),l=s(79184),d=s(25536);let c=(0,s(82075).A)("sessionStorage");function h(e,t){return!!e&&"assistive"===t}let u="restored-chat-messages";function p(e,t){if("childMessages"!==e&&"parentMessage"!==e)return t}function g(){c.removeItem(u)}var m=s(25641),E=s(4559),f=s(53419),_=s(73952),S=s(35247),T=s(79064),y=s(23657);let I=(e,t)=>{let s=t=>{t&&(T.Jt.selectedThreadID=t);let s=t!==e.selectedThreadID,r=T.Jt.getModel(t)?.id,a=e.availableModels?.find(e=>e.id===r)??e.model;return{...e,model:a,selectedThreadID:t,threadSelectedAt:s?new Date:e.threadSelectedAt,currentView:"thread",showTopicPicker:!t&&e.showTopicPicker,currentReferences:s?[]:e.currentReferences,threadHasNewMessages:!s&&e.threadHasNewMessages,editingMessage:s?void 0:e.editingMessage,pendingFirstMessage:s?void 0:e.pendingFirstMessage}};switch(t.type){case"SLASH_COMMANDS_ERROR":return(0,f.BI)("copilot.slash_commands_error"),{...e,slashCommandLoading:{...e.slashCommandLoading,state:"error"}};case"SLASH_COMMANDS_LOADED":return(0,f.BI)("copilot.slash_commands_loaded"),{...e,slashCommandLoading:{...e.slashCommandLoading,state:"loaded"}};case"SLASH_COMMANDS_LOADING":return{...e,slashCommandLoading:{...e.slashCommandLoading,state:"loading"}};case"OPEN_COPILOT_CHAT":return(0,f.BI)("copilot.open_copilot_chat",{source:t.source}),{...e,chatIsOpen:!0,chatIsVisible:!0,entryPointId:t.id};case"CLOSE_COPILOT_CHAT":return(0,f.BI)("copilot.close_copilot_chat"),{...e,chatIsOpen:!1};case"HIDE_COPILOT_CHAT":return(0,f.BI)("copilot.hide_copilot_chat"),{...e,chatIsVisible:!1};case"THREAD_CREATED":{let r=new Map(e.threads);return(0,f.BI)("copilot.thread_created",{...A(t.thread),mode:e.mode,count:r.size+1}),r.set(t.thread.id,t.thread),{...t.preventThreadSelection?e:s(t.thread.id),threads:r}}case"THREAD_CONTINUED":{let r=new Map(e.threads);return(0,f.BI)("copilot.thread_continued",{...A(t.thread),mode:e.mode,count:r.size+1}),r.set(t.thread.id,t.thread),{...s(t.thread.id),threads:r}}case"THREAD_CONTINUED_FAILED":return(0,f.BI)("copilot.thread_continued_failed",{stateSelectedThreadID:e.selectedThreadID,sharedIdOnFetch:e.fetchSharedThreads?.shareId,mode:e.mode}),{...e};case"SUGGESTIONS_GENERATED":return{...e,suggestions:t.suggestions};case"CLEAR_SUGGESTIONS":return{...e,suggestions:null};case"CLEAR_THREAD":return(0,f.BI)("copilot.clear_thread"),{...e,messages:[],currentReferences:[]};case"CLEAR_CURRENT_REFERENCES":{(0,f.BI)("copilot.clear_current_references");let s=t.keepTypes&&new Set(t.keepTypes),r=s?e.currentReferences.filter(e=>s.has(e.type)):[];return{...e,currentReferences:r}}case"CLEAR_ALL_REFERENCES":return(0,f.BI)("copilot.clear_all_references"),{...e,currentReferences:[]};case"MESSAGES_UPDATED":{let s=t.messages?[...t.messages]:[];if("error"===t.state&&(0,f.BI)("copilot.messages_updated",{count:t.messages?.length,loading:t.state}),!s)return{...e,messagesLoading:{...e.messagesLoading,state:t.state,missingOrgIds:t.missingOrgIds,notFound:t.notFound}};{let r=e.defaultRecipient,a=e.allClientConfirmations;for(let i of("loaded"===t.state&&s.length>0&&(r=v(s[s.length-1],e),a=s.map(e=>e.clientConfirmations?.map(e=>JSON.stringify(Object.values(e.confirmation).sort()))).flat().filter(Boolean)),s))i.clientSide=!1;let i=!1,n=!1;return S.W.planningAgent&&(n=s.some(e=>"planning-agent"===e.intent),i="loaded"===t.state),{...e,defaultRecipient:r,allClientConfirmations:a,messages:(0,_.zh)(s),messagesLoading:{...e.messagesLoading,state:t.state,missingOrgIds:t.missingOrgIds,notFound:t.notFound},messagesRestored:!1,...i&&{usePlanningIntent:n}}}}case"WAITING_ON_COPILOT":return{...e,isWaitingOnCopilot:t.loading,threadHasNewMessages:!0};case"WAITING_ON_ATTACHMENT":return{...e,isWaitingOnAttachment:t.loading,attachmentProcessingType:t.loading&&t.attachmentType||null};case"SELECT_THREAD":{(0,f.BI)("copilot.select_thread",{threadID:t.thread?.id,mode:e.mode});let r={...s(t.thread?.id||null),currentTopic:t.clearTopic?void 0:e.currentTopic,topicLoading:t.clearTopic?{error:null,state:"loaded"}:e.topicLoading};return null===t.thread&&e.currentRepository&&(r.currentReferences=[(0,m.qS)(e.currentRepository)]),r}case"HANDLE_EVENT_START":return(0,f.BI)("copilot.handle_event_start"),{...e,chatIsOpen:!0,chatIsVisible:!0,entryPointId:t.id,currentReferences:t.references??e.currentReferences};case"THREADS_LOADING":return{...e,threadsLoading:{...e.threadsLoading,state:"loading"}};case"DISMISS_ATTACH_KNOWLEDGE_BASE_HERE_POPOVER":return(0,f.BI)("copilot.dismiss_attach_knowledge_base_here_popover"),{...e,renderAttachKnowledgeBaseHerePopover:!1};case"DISMISS_KNOWLEDGE_BASE_ATTACHED_TO_CHAT_POPOVER":return(0,f.BI)("copilot.dismiss_knowledge_base_attached_to_chat_popover"),{...e,renderKnowledgeBaseAttachedToChatPopover:!1};case"KNOWLEDGE_BASES_LOADING":return{...e,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"loading"}};case"KNOWLEDGE_BASES_LOADED":return(0,f.BI)("copilot.knowledge_bases_loaded",{count:t.knowledgeBases.length}),{...e,knowledgeBases:t.knowledgeBases,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"loaded",error:null}};case"KNOWLEDGE_BASES_LOADING_ERROR":return(0,f.BI)("copilot.knowledge_bases_loading_error",{error:t.message}),{...e,knowledgeBasesLoading:{...e.knowledgeBasesLoading,state:"error",error:t.message}};case"LATEST_THREAD_LOADED":{let s=new Map(e.threads);return s.set(t.latestThread.id,t.latestThread),{...e,threads:s}}case"THREADS_LOADED":return(0,f.BI)("copilot.threads_loaded",{count:t.threads.length,mode:e.mode}),{...e,threadsLoading:{...e.threadsLoading,state:"loaded"},threads:new Map(t.threads.map(e=>[e.id,e]))};case"THREADS_LOADING_ERROR":return(0,f.BI)("copilot.threads_loading_error",{error:t.message}),{...e,threadsLoading:{error:t.message,state:"error",status:t.status}};case"DELETE_THREAD_KEEP_SELECTION":{let r=new Map(e.threads);return(0,f.BI)("copilot.thread_deleted",{...A(t.thread),count:r.size-1}),r.delete(t.thread.id),{...s(null),threads:r,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[],currentView:"list"}}case"DELETE_ALL_THREADS_KEEP_SELECTION":{let r=new Map(e.threads);for(let e of t.threads)(0,f.BI)("copilot.thread_deleted",{...A(e),count:r.size-1}),r.delete(e.id);return{...s(null),threads:r,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[],currentView:"list"}}case"DELETE_THREAD":{let r=new Map(e.threads);if((0,f.BI)("copilot.thread_deleted",{...A(t.thread),count:r.size-1,mode:e.mode}),r.delete(t.thread.id),e.selectedThreadID===t.thread.id)return{...s(null),threads:r,threadsLoading:{...e.threadsLoading,state:"loaded"},messages:[],messagesLoading:{state:"loaded",error:null},currentReferences:[]};return{...e,threads:r}}case"DELETE_THREAD_ERROR":{(0,f.BI)("copilot.delete_thread_error",{...A(t.thread),error:t.error});let s=new Map(e.threads);return s.set(t.thread.id,t.thread),{...e,threadsLoading:{...e.threadsLoading,error:t.error},threads:s}}case"DELETE_ALL_THREADS_ERROR":{for(let e of t.threads)(0,f.BI)("copilot.delete_thread_error",{...A(e),error:t.error});let s=new Map(e.threads);for(let e of t.threads)s.set(e.id,e);return{...e,threadsLoading:{...e.threadsLoading,error:t.error},threads:s}}case"MESSAGE_ADDED":{(0,f.BI)("copilot.message_added",{...C(t.message),count:e.messages.length+1,repoHasCustomInstructions:!!t.repoHasCustomInstructions,usedRepoCustomInstructions:!!t.usedRepoCustomInstructions,customInstructionsOwners:t.customInstructionsOwners||""});let s=(0,_.HR)(e.messages,t.message);return{...e,messages:s,messagesLoading:{state:"loaded",error:null},pendingFirstMessage:void 0,threadHasNewMessages:!0,editingMessage:void 0}}case"MESSAGE_FEEDBACK":{let s=[...e.messages],r=s.findIndex(e=>e.id===t.message.id),a=s[r];if(!a)return(0,f.BI)("copilot.message_feedback_no_message_found",{...C(t.message)}),e;return s[r]={...a,feedback:t.feedback},{...e,messages:s}}case"MESSAGES_SET_SELECTED_MESSAGE":{let s=(0,_.ws)(e.messages,t.message);return(0,f.BI)("copilot.chat_subthread_changed",{removedReferences:e.currentReferences.length}),{...e,messages:s,threadHasNewMessages:!1,threadSelectedAt:new Date}}case"MESSAGES_UNSELECT_PREVIOUS_MESSAGE":{let s=(0,_.TC)(e.messages,t.message);return{...e,messages:s,threadHasNewMessages:!1}}case"THREAD_UPDATED":return{...e,threads:R(e,t.thread)};case"REFERENCES_LOADED":return(0,f.BI)("copilot.references_loaded",{count:t.references.length}),{...e,currentReferences:e.currentReferences.filter(e=>t.references.every(t=>(0,m.Vb)(t)!==(0,m.Vb)(e))).concat(t.references)};case"ADD_REFERENCE":{let s=[...e.currentReferences.filter(e=>!(0,m.x_)(e,t.reference)),t.reference];return s.length>e.currentReferences.length&&((0,f.BI)("copilot.add_reference",{...w(t.reference),source:t.source,count:e.currentReferences.length+1}),"repository"===t.reference.type&&T.Jt.setLastUsedRepository(t.reference)),(t.reference&&"issue"===t.reference.type||"pull-request"===t.reference.type||"discussion"===t.reference.type)&&(0,E.i)(`Adding ${t.reference.type} ${t.reference.number} as a reference.`),{...e,currentReferences:s}}case"REMOVE_REFERENCES":{let s=t.references;s.length>0&&(0,f.BI)("copilot.remove_reference",{count:e.currentReferences.length-s.length}),s[0]&&("issue"===s[0].type||"pull-request"===s[0].type||"discussion"===s[0].type)&&(0,E.i)(`Removing ${s[0].type} ${s[0].number} as a reference.`);let r=T.Jt.getCurrentReferences(e.selectedThreadID);if(r){let t=r.filter(e=>!s.some(t=>(0,m.x_)(t,e)));T.Jt.setCurrentReferences(e.selectedThreadID,t)}return{...e,currentReferences:e.currentReferences.filter(e=>!s.includes(e))}}case"REPLACE_REFERENCE":{let s=[];for(let r of e.currentReferences)(0,m.x_)(r,t.referenceToDelete)?s.push(t.referenceToInsert):(0,m.x_)(r,t.referenceToInsert)||s.push(r);return(0,f.BI)("copilot.replace_reference",{removedReference:(0,m.Vb)(t.referenceToDelete),addedReference:(0,m.Vb)(t.referenceToInsert),count:s.length}),{...e,currentReferences:s}}case"SHOW_TOPIC_PICKER":return{...e,showTopicPicker:t.show};case"CURRENT_TOPIC_UPDATED":return t.topic&&(0,f.BI)("copilot.current_topic_updated",{type:t.topic?(0,m.P)(t.topic)?"docset":"repository":"none",mode:e.mode}),{...e,currentTopic:t.topic,topicLoading:{...e.topicLoading,state:t.state}};case"MESSAGE_STREAMING_STARTED":return(0,f.BI)("copilot.message_streaming_started",{...C(t.message),model:e.model?.id,mode:e.mode}),{...e,isWaitingOnCopilot:!0,streamingMessage:t.message,messages:[...e.messages]};case"MESSAGE_STREAMING_TOKEN_ADDED":return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,content:e.streamingMessage.content+t.token}:null};case"MESSAGE_STREAMING_FUNCTION_CALLED":if(e.streamingMessage){let s=e.streamingMessage.skillExecutions||[],r=s.findIndex(e=>"started"===e.status||"progress"===e.status),a=r>=0?s[r]:null,i=s,n=e.streamingMessage.references||[];switch(t.status){case"started":i=[...s,{slug:t.name,status:t.status,arguments:t.arguments,errorMessage:t.errorMessage,references:[]}];break;case"progress":if(a){let e={...a,status:t.status,statusMessage:t.statusMessage};i=[...s.slice(0,r),e,...s.slice(r+1)]}break;case"completed":a&&(i[r]={...a,status:t.status,references:t.references}),n=Array.from(new Set([...n,...t.references]));break;case"error":a&&(i[r]={...a,status:t.status,errorMessage:t.errorMessage})}return{...e,streamingMessage:{...e.streamingMessage,skillExecutions:i,references:n}}}return e;case"CLIENT_SKILL_CONFIRMATION_REQUEST":return{...e,clientSkillConfirmation:t.confirmation};case"CLIENT_SKILLS_REQUEST":return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,clientSkillsRequests:t.toolCalls}:null};case"READ_DOM_SKILL_INVOKED":return{...e,elementMap:t.elementMap};case"MESSAGE_STREAMING_COMPLETED":{let s,r=e.defaultRecipient,a=e.messages;return e.streamingMessage&&(r=v(s={...e.streamingMessage,id:t.messageResponse.id,references:t.messageResponse.references,createdAt:t.messageResponse.createdAt,intent:t.messageResponse.intent,copilotAnnotations:t.messageResponse.copilotAnnotations,parentMessageID:t.messageResponse.parentMessageID,model:t.messageResponse.model,clientSide:!1},e),(0,f.BI)("copilot.message_streaming_completed",{...C(s),...D(t.timings),model:e.model?.id,mode:e.mode,count:e.messages.length+1}),e.streamingMessage.requestID&&T.Jt.addRequestID(s.id,e.streamingMessage?.requestID),a=(0,_.Y$)(a,s),a=(0,_.HR)(a,s)),{...e,defaultRecipient:r,isWaitingOnCopilot:!1,streamingMessage:null,messages:a}}case"MESSAGE_STREAMING_FAILED":return(0,f.BI)("copilot.message_streaming_failed",{...e.streamingMessage?C(e.streamingMessage):{},...D(t.timings),model:e.model?.id,mode:e.mode}),{...e,isWaitingOnCopilot:!1,streamingMessage:null};case"MESSAGE_STREAMING_STOPPED":{let s,r=(0,_.B)(e.messages).findLast(e=>"user"===e.role)?.id;e.streamingMessage?(s={...e.streamingMessage,interrupted:!0,parentMessageID:r},(0,f.BI)("copilot.message_streaming_stopped",{...C(s),...D(t.timings),model:e.model?.id,mode:e.mode,count:e.messages.length+1})):e.isWaitingOnCopilot&&(s={id:crypto.randomUUID(),role:"assistant",threadID:e.selectedThreadID??"",references:[],createdAt:new Date().toISOString(),interrupted:!0,clientSide:!0,parentMessageID:r});let a=e.messages;if(null!=s){let e=a.findLast(e=>"user"===e.role);void 0!==e&&(s.parentMessageID=e.id),a=(0,_.HR)(a,s)}return{...e,isWaitingOnCopilot:!1,streamingMessage:null,messages:a}}case"MESSAGES_CLEAR_LAST_ERROR":{let t=(0,_.B)(e.messages),s=e.messages,r=t[t.length-1],a=r?.error||r?.interrupted,i=s;return a&&(i=s.filter(e=>e.id!==r?.id)),{...e,streamingMessage:null,messages:[...i]}}case"SELECT_REFERENCE":return t.reference&&(0,f.BI)("copilot.select_reference",w(t.reference)),{...e,selectedReference:t.reference};case"MODELS_LOADING":return{...e,modelsLoading:{state:"loaded",error:null}};case"MODELS_LOADING_ERROR":return{...e,modelsLoading:{state:"error",error:t.error}};case"MODELS_LOADED":{let s=t.models;return S.W.visionAllowedInClaude||(s=t.models.map(e=>{if(e.id.startsWith("claude")){let t={...e};return t.capabilities.supports.vision=!1,t}return e})),{...e,model:(s||[]).find(t=>t.id===e.model.id)||e.model,availableModels:s||[]}}case"SELECT_MODEL":{if("immersive"!==e.mode)return e;let s=t.model?.capabilities?.supports?.vision?e.currentReferences:e.currentReferences.filter(e=>"image"!==e.type);return(0,f.BI)("copilot.select_model",{model:t.model?.name,mode:e.mode}),{...e,model:t.model,currentReferences:s}}case"VIEW_ALL_THREADS":return{...e,currentView:"list"};case"VIEW_CURRENT_THREAD":return{...e,currentView:"thread"};case"IMPLICIT_CONTEXT_UPDATED":if(!(0,m.yR)(t.context,e.context))return{...e,context:t.context};return e;case"SET_TOP_REPOSITORIES":return{...e,topRepositoriesCache:t.topics};case"SET_AGENTS":return{...e,agents:t.agents};case"SET_CUSTOM_COPILOT":{let s=e.customCopilots?.find(e=>(0,y.UG)(e,t.customCopilot)),r=s&&t.partial,a=s?e.customCopilots?.map(e=>(0,y.UG)(e,s)?r?{...e,...t.customCopilot}:t.customCopilot:e):[...e.customCopilots??[],t.customCopilot];return{...e,customCopilots:a}}case"SET_CUSTOM_COPILOTS":return{...e,customCopilots:t.customCopilots};case"REMOVE_CUSTOM_COPILOT":return{...e,customCopilots:e.customCopilots?.filter(e=>!(0,y.UG)(e,t.customCopilotId))};case"SET_DEEP_CODESEARCH":return{...e,skillOptions:{...e.skillOptions,deepCodeSearch:t.deepCodeSearch}};case"MESSAGE_STREAMING_CONFIRMATION":{let s={title:t.title,message:t.message,confirmation:t.confirmation};return{...e,streamingMessage:e.streamingMessage?{...e.streamingMessage,confirmations:e.streamingMessage.confirmations?[...e.streamingMessage.confirmations,s]:[s]}:null}}case"AGENT_ERROR":{let s=e.streamingMessage,r=t.error;return{...e,streamingMessage:s&&{...s,agentErrors:[...s.agentErrors??[],{type:r.type,code:r.code,message:r.message,identifier:r.identifier}]}}}case"ENTITLEMENT_UPDATED":return{...e,entitlement:t.entitlement??e.entitlement};case"TOGGLE_REPO_CUSTOM_INSTRUCTIONS":return(0,f.BI)("copilot.repo_custom_instructions_toggled",{isEnabling:!!t.value}),{...e,repoCustomInstructionsEnabled:t.value};case"DISMISS_EDITOR_UPSELL_BANNER":return{...e,isEditorUpsellBannerDismissed:!0};case"DISMISS_AMBIENT_ERROR":return{...e,ambientError:null};case"ADD_AMBIENT_ERROR":return{...e,ambientError:{message:t.message}};case"SET_PERSONAL_INSTRUCTIONS":return{...e,personalInstructions:t.personalInstructions};case"SHARED_THREAD_UPDATED":{let s=R(e,t.thread),r=s.get(t.thread.id);return r&&(0,f.BI)("copilot.shared_thread_update",A(r)),{...e,threads:s}}case"SHARED_THREADS_LOADING":return{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"loading"}};case"SHARED_THREADS_LOADED":return(0,f.BI)("copilot.shared_threads_loaded"),{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"loaded"}};case"SHARED_THREADS_LOADING_ERROR":return(0,f.BI)("copilot.shared_threads_loading_error",{error:t.message}),{...e,sharedThreadsLoading:{...e.sharedThreadsLoading,state:"error",error:t.message}};case"IMAGE_UPLOADED":return{...e,currentReferences:e.currentReferences.map(e=>"image"===e.type&&e.id===t.referenceId?{...e,imageUrl:t.dotcomAttachment.previewUrl}:e)};case"START_EDITING_MESSAGE":return(0,f.BI)("dotcom_chat.activate",{target:"USER_MESSAGE_ACTION_EDIT",mode:"immersive"}),{...e,editingMessage:t.messageId};case"CANCEL_EDITING_MESSAGE":return{...e,editingMessage:void 0};case"FETCH_SHARED_THREAD_MESSAGES":return{...e,fetchSharedThreads:{ok:t.ok,status:t.status,shareId:t.shareId,originalThreadId:t.originalThreadId}};case"SET_WRAP_CODE_LINES":return{...e,wrapCodeLines:t.value};case"CLEAR_SHARED_THREAD_CHANNEL":return{...e,sharedThreadChannel:null};case"CLEAR_DEFAULT_RECIPIENT":return{...e,defaultRecipient:void 0};case"SET_PENDING_FIRST_MESSAGE":return{...e,pendingFirstMessage:t.message};case"SET_USE_PLANNING_INTENT":return{...e,usePlanningIntent:t.value}}};function R(e,t){let s=new Map(e.threads),r=e.threads.get(t.id);if(!r)return s;let a={...r,...t};return s.set(t.id,a),s}function C(e){var t;if(!e)return(0,f.Ti)({});let s={id:e.id,role:e.role,createdAt:e.createdAt,threadID:e.threadID,referenceCount:e.references?.length??0};return e.intent&&(s.intent=e.intent),e.error&&(s.error=e.error),e.copilotAnnotations&&(s.copilotAnnotations=function(e){if(e)return{CodeVulnerability:e.CodeVulnerability?.map(e=>({details:{type:e?.details?.type}})),PublicCodeReference:e.PublicCodeReference?.map(e=>({details:{license:e?.details?.license,language:e?.details?.language}}))}}(e.copilotAnnotations)),e.skillExecutions&&(s.skillExecutions=(t=e.skillExecutions)?t.map(e=>({slug:e?.slug,status:e?.status,argumentCount:e?.arguments?.length??0,errorMessage:e?.errorMessage,references:e?.references?.length??0})):[]),e.interrupted&&(s.interrupted=!0),(0,f.Ti)(s)}function A(e){return e?(0,f.Ti)({id:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,currentReferenceCount:e.currentReferences?.length??0}):(0,f.Ti)({})}function w(e){return e?(0,f.Ti)({type:e.type}):(0,f.Ti)({})}function D(e){let t={totalTime:e.endTime-e.startTime};return void 0!==e.firstByte&&(t.ttfb=e.firstByte-e.startTime),void 0!==e.firstToken&&(t.ttft=e.firstToken-e.startTime),t}function v(e,t){let s=(0,m.Th)(e,t.currentUserLogin);if("agent"===s.type)return s.name}var M=s(33592),L=s(46062),O=s(72206);let b=(0,o.createContext)(null);function N(e){let t,s,i,n,E,f,S,y,R,C=(0,a.c)(72),{children:A,topic:w,workerPath:D,threadId:v,refs:O,selectedReference:N,mode:k,ssoOrganizations:x,chatIsOpen:B,chatIsVisible:G,chatVisibleSettingPath:H,agents:U,customCopilots:F,messages:$,testReducerState:W,realIp:K,currentView:q,copilotChatPayload:V}=e,J=function(e,t){let s,r,i,n=(0,a.c)(4),l=h(e,t);if(n[0]===Symbol.for("react.memo_cache_sentinel")){let e=c.getItem(u);s=e?JSON.parse(e):void 0,n[0]=s}else s=n[0];let d=s;if(n[1]===Symbol.for("react.memo_cache_sentinel")?(r=[],n[1]=r):r=n[1],(0,o.useEffect)(g,r),l&&d?.expiry&&d.expiry>Date.now()&&d.threadId===e){let e;return n[2]===Symbol.for("react.memo_cache_sentinel")?(e={restoredMessages:d.restoredMessages,restoredThreadTitle:d.threadTitle},n[2]=e):e=n[2],e}return n[3]===Symbol.for("react.memo_cache_sentinel")?(i={},n[3]=i):i=n[3],i}(v,k),j=J.restoredMessages,z=J.restoredThreadTitle;if(j){let e;C[0]!==j?(e=(0,_.zh)(j),C[0]=j,C[1]=e):e=C[1],j=e}C[2]!==w?(t=w?(0,m.qS)(w):void 0,C[2]=w,C[3]=t):t=C[3];let Q=t;C[4]===Symbol.for("react.memo_cache_sentinel")?(s=(0,L.fZ)(null,null),C[4]=s):s=C[4];let Y=s;C[5]!==U||C[6]!==B||C[7]!==G||C[8]!==H||C[9]!==V.agentsEnabled||C[10]!==V.agentsPath||C[11]!==V.apiURL||C[12]!==V.autoSubmit||C[13]!==V.currentUserLogin||C[14]!==V.customCopilotsEnabled||C[15]!==V.customInstructions||C[16]!==V.hasCEorCBAccess||C[17]!==V.optedInToPreviewFeatures||C[18]!==V.optedInToUserFeedback||C[19]!==V.personalInstructions||C[20]!==V.plan||C[21]!==V.renderAttachKnowledgeBaseHerePopover||C[22]!==V.renderBetaLabel||C[23]!==V.renderKnowledgeBaseAttachedToChatPopover||C[24]!==V.renderKnowledgeBases||C[25]!==V.reviewLab||C[26]!==V.sharedThreadChannel||C[27]!==V.thirdPartyMcpAllowed||C[28]!==q||C[29]!==F||C[30]!==$||C[31]!==k||C[32]!==O||C[33]!==j||C[34]!==z||C[35]!==N||C[36]!==x||C[37]!==W||C[38]!==v||C[39]!==w||C[40]!==Q||C[41]!==D?(i=W||{threadSelectedAt:new Date,threadsLoading:{state:"pending",error:null},messagesLoading:{state:"pending",error:null},messagesRestored:!!j,slashCommandLoading:{state:"pending",error:null},showTopicPicker:"immersive"!==k&&(!v||"assistive"===k)&&!w,topicLoading:{state:"pending",error:null},threads:new Map,restoredThreadTitle:z,knowledgeBasesLoading:{state:"pending",error:null},knowledgeBases:[],model:Y,availableModels:[Y],modelsLoading:{state:"pending",error:null},messages:$??j??[],streamingMessage:null,selectedThreadID:v,currentTopic:void 0,chatIsOpen:!!B,isWaitingOnCopilot:!1,isWaitingOnAttachment:!1,attachmentProcessingType:null,currentUserLogin:V.currentUserLogin,apiUrl:V.apiURL,currentReferences:Q?[Q,...O]:O,findFileWorkerPath:D,currentView:q||"thread",selectedReference:N??null,mode:k,currentRepository:w,ssoOrganizations:x,context:void 0,renderKnowledgeBases:V.renderKnowledgeBases??!0,renderAttachKnowledgeBaseHerePopover:V.renderAttachKnowledgeBaseHerePopover,renderKnowledgeBaseAttachedToChatPopover:V.renderKnowledgeBaseAttachedToChatPopover,customInstructions:V.customInstructions,chatIsVisible:G,chatVisibleSettingPath:H,renderBetaLabel:V.renderBetaLabel,topRepositoriesCache:void 0,agentsPath:V.agentsPath,customCopilotsEnabled:V.customCopilotsEnabled??!1,optedInToPreviewFeatures:V.optedInToPreviewFeatures,optedInToUserFeedback:V.optedInToUserFeedback,agents:U,customCopilots:F,reviewLab:V.reviewLab,repoCustomInstructionsEnabled:T.Jt.getRepoCustomInstructionsState(),ambientError:void 0,personalInstructions:V.personalInstructions??null,threadHasNewMessages:!1,sharedThreadsLoading:{state:"pending",error:null},skillOptions:{deepCodeSearch:!1},wrapCodeLines:T.Jt.getWrapCodeLines(),sharedThreadChannel:V.sharedThreadChannel,autoSubmit:V.autoSubmit??!1,thirdPartyMcpAllowed:V.thirdPartyMcpAllowed??!1,plan:V.plan,hasCEorCBAccess:V.hasCEorCBAccess,agentsEnabled:V.agentsEnabled},C[5]=U,C[6]=B,C[7]=G,C[8]=H,C[9]=V.agentsEnabled,C[10]=V.agentsPath,C[11]=V.apiURL,C[12]=V.autoSubmit,C[13]=V.currentUserLogin,C[14]=V.customCopilotsEnabled,C[15]=V.customInstructions,C[16]=V.hasCEorCBAccess,C[17]=V.optedInToPreviewFeatures,C[18]=V.optedInToUserFeedback,C[19]=V.personalInstructions,C[20]=V.plan,C[21]=V.renderAttachKnowledgeBaseHerePopover,C[22]=V.renderBetaLabel,C[23]=V.renderKnowledgeBaseAttachedToChatPopover,C[24]=V.renderKnowledgeBases,C[25]=V.reviewLab,C[26]=V.sharedThreadChannel,C[27]=V.thirdPartyMcpAllowed,C[28]=q,C[29]=F,C[30]=$,C[31]=k,C[32]=O,C[33]=j,C[34]=z,C[35]=N,C[36]=x,C[37]=W,C[38]=v,C[39]=w,C[40]=Q,C[41]=D,C[42]=i):i=C[42];let X=i,[Z,ee]=(0,o.useReducer)(I,X);return!function(e,t,s,r){let i,n,l,d=(0,a.c)(9);d[0]!==r||d[1]!==t?(i=h(t,r),d[0]=r,d[1]=t,d[2]=i):i=d[2];let g=i;d[3]!==e||d[4]!==g||d[5]!==t||d[6]!==s?(n=()=>{if(!g)return;let r=()=>{if(!e?.length||!t)return;let r=s.get(t),a=r?.name,i={expiry:Date.now()+8e3,restoredMessages:e,threadId:t,threadTitle:a};c.setItem(u,JSON.stringify(i,p))};return window.addEventListener("turbo:before-fetch-response",r),window.addEventListener("beforeunload",r),window.addEventListener("popstate",r),()=>{window.removeEventListener("turbo:before-fetch-response",r),window.removeEventListener("beforeunload",r),window.removeEventListener("popstate",r)}},l=[e,g,t,s],d[3]=e,d[4]=g,d[5]=t,d[6]=s,d[7]=n,d[8]=l):(n=d[7],l=d[8]),(0,o.useEffect)(n,l)}(Z.messages,Z.selectedThreadID,Z.threads,Z.mode),C[43]!==Z.chatIsOpen||C[44]!==Z.currentReferences||C[45]!==Z.currentRepository?.id||C[46]!==Z.selectedThreadID?(n=function(){if(!Z.chatIsOpen)return;let e=Z.currentReferences.filter(e=>"repository"!==e.type||e.id!==Z.currentRepository?.id);T.Jt.setCurrentReferences(Z.selectedThreadID,e)},C[43]=Z.chatIsOpen,C[44]=Z.currentReferences,C[45]=Z.currentRepository?.id,C[46]=Z.selectedThreadID,C[47]=n):n=C[47],C[48]!==Z.chatIsOpen||C[49]!==Z.currentReferences||C[50]!==Z.currentRepository||C[51]!==Z.selectedThreadID?(E=[Z.selectedThreadID,Z.currentReferences,Z.currentRepository,Z.chatIsOpen],C[48]=Z.chatIsOpen,C[49]=Z.currentReferences,C[50]=Z.currentRepository,C[51]=Z.selectedThreadID,C[52]=E):E=C[52],(0,o.useEffect)(n,E),C[53]!==A||C[54]!==Z.selectedThreadID?(f=(0,r.jsx)(d.M,{selectedThreadId:Z.selectedThreadID,children:A}),C[53]=A,C[54]=Z.selectedThreadID,C[55]=f):f=C[55],C[56]!==V.apiURL||C[57]!==V.apiVersion||C[58]!==V.hasCEorCBAccess||C[59]!==K||C[60]!==x||C[61]!==Z||C[62]!==f?(S=(0,r.jsx)(b.Provider,{value:ee,children:(0,r.jsx)(M.v,{apiURL:V.apiURL,apiVersion:V.apiVersion,state:Z,dispatch:ee,ssoOrganizations:x,realIp:K,hasCEorCBAccess:V.hasCEorCBAccess,children:f})}),C[56]=V.apiURL,C[57]=V.apiVersion,C[58]=V.hasCEorCBAccess,C[59]=K,C[60]=x,C[61]=Z,C[62]=f,C[63]=S):S=C[63],C[64]!==Z||C[65]!==S?(y=(0,r.jsx)(P,{state:Z,children:S}),C[64]=Z,C[65]=S,C[66]=y):y=C[66],C[67]!==V.licenseType||C[68]!==V.plan||C[69]!==V.quotas||C[70]!==y?(R=(0,r.jsx)(l.$d,{initialLicenseType:V.licenseType,initialPlan:V.plan,initialQuotas:V.quotas,children:y}),C[67]=V.licenseType,C[68]=V.plan,C[69]=V.quotas,C[70]=y,C[71]=R):R=C[71],R}let k=(0,o.createContext)(null);function P(e){let t,s,o,l,d=(0,a.c)(14),{state:c,children:h}=e,[u,p]=(0,i.XG)(c);return d[0]!==p||d[1]!==c||d[2]!==u.current.value?(t=()=>{c!==u.current.value&&p(c)},d[0]=p,d[1]=c,d[2]=u.current.value,d[3]=t):t=d[3],d[4]!==p||d[5]!==c||d[6]!==u?(s=[c,u,p],d[4]=p,d[5]=c,d[6]=u,d[7]=s):s=d[7],(0,n.N)(t,s),d[8]!==h||d[9]!==c?(o=(0,r.jsx)(k.Provider,{value:c,children:h}),d[8]=h,d[9]=c,d[10]=o):o=d[10],d[11]!==u||d[12]!==o?(l=(0,r.jsx)(O.sw,{value:u,children:o}),d[11]=u,d[12]=o,d[13]=l):l=d[13],l}function x(){let e=(0,o.useContext)(k);if(!e)throw Error("useChatState can only be used inside a CopilotChatProvider");return e}function B(){return(0,o.useContext)(k)??void 0}function G(e){let t=(0,O.rE)();if(!t||!t.current)throw Error("useChatStateLens can only be used inside a CopilotChatProvider");let s=(0,i.Sk)(t.current,e);return(0,i.HN)(s)}function H(e){let t,s=(0,a.c)(2);return s[0]!==e?(t=t=>t[e],s[0]=e,s[1]=t):t=s[1],G(t)}function U(...e){let t,s=(0,a.c)(2);return s[0]!==e?(t=t=>(function(e,t){let s={};for(let r of t)s[r]=e[r];return s})(t,e),s[0]=e,s[1]=t):t=s[1],G(t)}function F(){let e=(0,o.useContext)(b);if(!e)throw Error("useChatDispatch can only be used inside a CopilotChatProvider");return e}try{b.displayName||(b.displayName="CopilotChatDispatchContext")}catch{}try{N.displayName||(N.displayName="CopilotChatProvider")}catch{}try{k.displayName||(k.displayName="ChatStateContext")}catch{}try{P.displayName||(P.displayName="ChatStateProvider")}catch{}},6219:(e,t,s)=>{s.d(t,{BV:()=>i,My:()=>o,QM:()=>n,ZK:()=>GenericServerError});var r=s(50467),a=s(96379);async function i(e,t,s){let r=await (0,a.DI)(t,{method:"POST",body:l(e),signal:s}),i=await r.json();if(!r.ok)throw new GenericServerError("Error creating policy",i.errors);if(!i.asset_upload_url)throw Error("Unexpected error, missing asset upload URL");return i}async function n(e,t,s){let r=await fetch(t.upload_url,{method:"POST",body:l({...t.form,file:e}),signal:s});if(!r.ok)throw Error(await r.text())}async function o(e,t){let s=await (0,a.DI)(e.asset_upload_url,{method:"PUT",signal:t}),r=await s.json();if(!s.ok)throw new GenericServerError("Error completing the upload",r.errors);return r}let GenericServerError=class GenericServerError extends Error{constructor(e,t){super(e),(0,r._)(this,"errors",void 0),this.name="GenericServerError",this.errors=t}};function l(e){let t=new FormData;for(let[s,r]of Object.entries(e).filter(([,e])=>null!=e))t.append(s,r);return t}},11053:(e,t,s)=>{s.d(t,{KD:()=>h,PW:()=>c,WN:()=>u,Wd:()=>i,ic:()=>m,iw:()=>d,sy:()=>g,tH:()=>l,uY:()=>p});var r=s(25407),a=s(68074);let i="edit";function n({owner:e,repo:t,pullNumber:s}){return`/${encodeURIComponent(e)}/${encodeURIComponent(t)}/pull/${s}`}function o({owner:e,repo:t,pullNumber:s}){return`${n({owner:e,repo:t,pullNumber:s})}/${i}`}function l({owner:e,repo:t,pullNumber:s,location:r}){return o({owner:e,repo:t,pullNumber:s})+(r?.search||"")}function d({owner:e,repo:t,pullNumber:s,path:a,location:i}){return`${o({owner:e,repo:t,pullNumber:s})}/file/${(0,r.QU3)(a)}`+(i?.search||"")}function c({owner:e,repo:t,pullNumber:s}){return`${n({owner:e,repo:t,pullNumber:s})}/workspace_editor/suggestions`}function h({owner:e,repo:t,pullNumber:s,pullRequestReviewCommentId:r}){return`${n({owner:e,repo:t,pullNumber:s})}/workspace_editor/suggestions/${r}`}function u({commitOid:e,owner:t,repo:s,pullNumber:r,path:a,location:i}){return`${n({owner:t,repo:s,pullNumber:r})}/workspace_editor/files/${encodeURIComponent(e)}/${encodeURIComponent(a)}`+(i?.search||"")}function p({owner:e,repo:t,pullNumber:s,location:r,path:i}){let n=`${o({owner:e,repo:t,pullNumber:s})}/new`,l=new URLSearchParams(r?.search||"");if(i&&i.includes("/")){let e=i.substring(0,i.lastIndexOf("/")+1);l.set(a.t,e)}return n+(l.toString()?`?${l.toString()}`:"")}function g({owner:e,repo:t,pullNumber:s}){return`${o({owner:e,repo:t,pullNumber:s})}/commit_changes`}function m({owner:e,repo:t,pullNumber:s,analyzeDiffs:r=!1,detectRisk:a=!1}){let i=`${n({owner:e,repo:t,pullNumber:s})}/diff`,o=new URLSearchParams({analyze_diffs:r.toString(),detect_risk:a.toString()});return`${i}?${o.toString()}`}},16946:(e,t,s)=>{s.d(t,{e8:()=>CopilotChatManager,L9:()=>O});var r,a=s(50467),i=s(74848),n=s(79802),o=s(53419),l=s(40104),d=s(96379),c=s(38627),h=s(26239),u=s(25641),p=s(86339),g=s(20139),m=s(73952),E=s(51213),f=s(35247),_=s(79064),S=s(57872),T=s(72303),y=s(46062),I=s(69599);let R={interactDomSkillHighlight:"interact-dom-module__interactDomSkillHighlight--gcLAQ"};let InteractDomSkill=class InteractDomSkill{requiresConfirmation(){return"click"===JSON.parse(this.rawArguments).action}confirmationMessage(){let e=JSON.parse(this.rawArguments),t="";switch(e.action){case"click":t=`Click on ${e.element}`;break;case"type":t=`Type "${e.value}" into ${e.element}`}return t}static schema(){return{type:"function",function:{name:"interact-dom",description:"This function gives you the ability to interact with the DOM. Perform an action like clicking on an element, typing into an input, or filling out a form on the current html page. Call this function to fulfill the user request after receiving the current url and tag map of accessible element names to their tags from invoking the read-dom function. For the type action, if there is existing text in the element (passed in the tag map), you should modify that text how the user requests and return the new text contents. Do no just return the new text the user asked you to type unless they are explicitly trying to overwrite the current value. Afterwards, you should send a message letting the user know the actions you performed. If the user makes multiple requests in one message, you should invoke this function multiple times in a single reposnse.",parameters:{type:"object",required:["action","element"],properties:{action:{type:"string",description:'The DOM action to take on an element on the current page. The action property can either be "click" or "type". If it is "type" then the value property should be the string to type into the input element.'},element:{type:"string",description:"The accessible name of the element to perform the DOM action on. This must be one of the keys in the tag map returned from read-dom."},value:{type:"string",description:"If the action is 'type', then value is the string to type into the text input element. The text input's value will be set to this, so if the element has an existing value from the tag map passed in, make sure to include that in this paramter."}}}}}}async execute(){try{let e=JSON.parse(this.rawArguments),t=this.chatState?.elementMap?.get(e.element),s="";if(t instanceof HTMLElement)switch(t.classList.add(R.interactDomSkillHighlight),document.addEventListener("click",()=>{t.classList.remove(R.interactDomSkillHighlight)},{once:!0}),e.action){case"click":t.click(),s=`${e.element} was clicked.`;break;case"type":"value"in t?(t.value="",await function(e,t,s=0){return new Promise(r=>{!function s(a){if(as(a+1),10)}else{let t=new Event("input",{bubbles:!0});e.dispatchEvent(t),r()}}(s)})}(t,e.value||""),s=`${e.value} was typed into ${e.element}.`):s=`${e.element} could not be typed into because it was not an element that accepts a value like textarea or input.`}else s=`${e.element} could not be located.`;return{result:s,ok:!0}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:`Error executing ${this.name} skill`}`}}}constructor(e,t,s,r){(0,a._)(this,"id",void 0),(0,a._)(this,"name",void 0),(0,a._)(this,"rawArguments",void 0),(0,a._)(this,"chatState",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=r}};let C={workbench:!0};let NavigateInternallySkill=class NavigateInternallySkill{requiresConfirmation(){return!1}confirmationMessage(){return"Navigate to the specified location"}static schema(){return{type:"function",function:{name:"navigate-internally",description:` This tool is used to redirect the user to a handful of internal locations that have been predefined. Only the predefined list of locations will be allowed, and any other location will be rejected and cause an error. Locations are defined as [slug]: [description]. Use the slug when calling this tool. Locations: - workbench: A specialized location for helping the user with creating, building, testing, and running code, websites and more. This area should be preferred for any situation where the user wants to build an app, website, or do any sort of extensive coding. `,parameters:{type:"object",required:["location","reasoning"],properties:{location:{description:"The location slug to navigate the user.",type:"string",enum:["workbench"]},reasoning:{type:"string",description:`The reasoning for why this task is a good candidate for the location. We will display this to the user for confirmation. This field should be formatted as follows: "We think this would be a good task for [location] [because] ." `}}}}}}execute(){try{let e=JSON.parse(this.rawArguments);if(!this.chatState?.selectedThreadID)return{ok:!1,result:"No active thread found. Cannot redirect."};if(!C[e.location])return{ok:!1,result:`Location ${e.location} is not valid.`};if("workbench"!==e.location)return{ok:!1,result:"Location is not valid."};{let e=this.chatState?.messages.find(e=>"user"===e.role&&"temp"===e.threadID);if(!e||!e.content)return{ok:!1,result:"We couldn't find the last user message, so we can't redirect, let's build here"};let t=encodeURIComponent(e.content);return window.location.href=`/copilot/spark?initialPrompt=${t}`,{ok:!0,result:"The user is now in the workbench. Our job is done, wish them luck in less than 5 words."}}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:"Error executing redirect to workbench"}`}}}constructor(e,t,s,r,i){(0,a._)(this,"id",void 0),(0,a._)(this,"name",void 0),(0,a._)(this,"rawArguments",void 0),(0,a._)(this,"chatState",void 0),(0,a._)(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=r,this.dispatch=i}};var A=s(6786);let ReadDomSkill=class ReadDomSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Read the DOM for the current page"}static schema(){return{type:"function",function:{name:"read-dom",description:"Allows you to interact with the DOM to perform actions like filling out forms, submitting forms, clicking on buttons, and typing into inputs on the current web page. This function requests a list of all interactable elements on the current html page, keyed by their accessible name. If the user makes a request to interact with elements on the current web page, but has not provided any DOM elements in clientToolResults, call this function. After the results are returned, call interact-dom to actually perform the desired interactions. If the user asks a question about the DOM, you can call this to read its state, but do not follow up with an interact-dom function call in that case. Finally, let the user know what actions you performed",parameters:{type:"object",properties:{}}}}}execute(){try{let e={},t=new Map;for(let s of document.querySelectorAll('input, select, textarea, button, [role="button"], a, [tabindex]')){let r=(0,A.G3)(s);t.set(r,s);let a=s.tagName,i=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement?s.value:null;e[r]={tag:a,value:i}}return this.dispatch?.({type:"READ_DOM_SKILL_INVOKED",elementMap:t}),{result:JSON.stringify({tagMap:e,url:window.location.href}),ok:!0}}catch(e){return{ok:!1,result:`Error: ${e instanceof Error?e.message:`Error executing ${this.name} skill`}`}}}constructor(e,t,s,r,i){(0,a._)(this,"id",void 0),(0,a._)(this,"name",void 0),(0,a._)(this,"rawArguments",void 0),(0,a._)(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.dispatch=i}};var w=s(39689);let D=/^\/settings\/.*/,v={"read-local-workspace-file":{constructor:w.K,schema:w.K.schema(),includePaths:[/^\/[^/]+\/[^/]+\/pull\/\d+\/edit$/],featureFlag:"workspace_editor_fix_a_build_function_calling"},"read-dom":{constructor:ReadDomSkill,schema:ReadDomSkill.schema(),excludePaths:[D],featureFlag:"copilot_client_dom_skills"},"interact-dom":{constructor:InteractDomSkill,schema:InteractDomSkill.schema(),excludePaths:[D],featureFlag:"copilot_client_dom_skills"},"navigate-internally":{constructor:NavigateInternallySkill,schema:NavigateInternallySkill.schema(),includePaths:[/^\/copilot(\/.*)?$/],featureFlag:"copilot_workbench_redirect"}};let UnknownClientSkill=class UnknownClientSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Unknown function"}execute(){return{ok:!0,result:`Unknown function: ${this.name} called with args: ${this.rawArguments}`}}schema(){return{type:"function",function:{name:"unknown-client-skill",description:"This is a fallback skill if the skill is not found"}}}constructor(e,t,s,r,i){(0,a._)(this,"id",void 0),(0,a._)(this,"name",void 0),(0,a._)(this,"rawArguments",void 0),(0,a._)(this,"chatState",void 0),(0,a._)(this,"dispatch",void 0),this.id=e,this.name=t,this.rawArguments=s,this.chatState=r,this.dispatch=i}};let SkillExecutor=class SkillExecutor{async run(){if(this.requiresConfirmation()){let e=this.clientSkillConfirmation();this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:e})}else await this.executeSkills()}setParentMessageId(e){this.parentMessageId=e}resetExecution(){this.parentMessageId=void 0,this.skillsToExecute=[]}clientSkillConfirmation(){return{title:"Confirm actions",message:this.confirmationMessage(),onSubmit:e=>{this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:void 0}),e?this.executeSkills():this.sendChatMessage({thread:this.thread,content:"",references:[],clientToolResults:this.confirmationDeclinedResults()}),this.resetExecution()},confirmation:{toolCalls:this.toolCalls}}}confirmationDeclinedResults(){return this.skillsToExecute.map(e=>({id:e.id,type:"function",functionCallResult:{name:e.name,arguments:e.rawArguments,result:`Failed to execute ${e.name}: Permission denied by user`}}))}validateSkillEntry(e){if(e&&(!e.featureFlag||(0,I.G7)(e.featureFlag)))return e.constructor}toolCallsToSkills(){return this.toolCalls.map(e=>{let t=v[e.function.name],s=this.validateSkillEntry(t);return s?new s(e.id,e.function.name,e.function.arguments,this.chatState,this.dispatch):new UnknownClientSkill(e.id,e.function.name,e.function.arguments,void 0,void 0)})}requiresConfirmation(){return this.skillsToExecute.some(e=>e.requiresConfirmation())}confirmationMessage(){let e="";for(let t of this.skillsToExecute)e+=`${t.confirmationMessage()} `;return e}async executeSkills(){if(0===this.skillsToExecute.length)return;let e=[];for(let t of this.skillsToExecute){let s=await this.executeSkill(t),r={id:t.id,type:"function",functionCallResult:s};e.push(r)}this.sendChatMessage({thread:this.thread,content:"",references:[],clientToolResults:e,parentMessageId:this.parentMessageId}),this.resetExecution()}async executeSkill(e){try{let{ok:t,result:s}=await e.execute();return(0,o.BI)("dotcom_chat.client_skill_execution",{skillName:e.name,success:t}),{name:e.name,arguments:e.rawArguments,result:s}}catch{return(0,o.BI)("dotcom_chat.client_skill_execution",{skillName:e.name,success:!1}),{name:e.name,arguments:e.rawArguments,result:`Failed to execute ${e.name}`}}}constructor(e,t,s,r,i){(0,a._)(this,"toolCalls",void 0),(0,a._)(this,"sendChatMessage",void 0),(0,a._)(this,"thread",void 0),(0,a._)(this,"skillsToExecute",void 0),(0,a._)(this,"chatState",void 0),(0,a._)(this,"dispatch",void 0),(0,a._)(this,"parentMessageId",void 0),this.thread=e,this.toolCalls=t,this.sendChatMessage=s,this.chatState=r,this.dispatch=i,this.skillsToExecute=this.toolCallsToSkills()}};var M=s(63828),L=s(30456);let O=99,b="Only one agent is allowed per thread, and their context can't be shared. If you want to interact with another agent, please start a new thread and @ mention the new agent.",N=null;let CopilotChatManager=class CopilotChatManager{async openChat(e,t,s,r,a){if(this.dispatch({type:"OPEN_COPILOT_CHAT",source:s}),"thread"===t&&await this.findOrStartNewThread(e,a),_.Jt.setCollapsedState(!1),B(this.getChatState().entryPointId??h.fv,!0),r){let e=new FormData;e.set("copilot_chat_visible","true"),(0,d.DI)(r,{method:"PUT",body:e})}}closeChat(){this.dispatch({type:"CLOSE_COPILOT_CHAT"}),_.Jt.setCollapsedState(!0),B(this.getChatState().entryPointId??h.fv,!1)}hideChat(e){if(this.dispatch({type:"HIDE_COPILOT_CHAT"}),this.closeChat(),e){let t=new FormData;t.set("copilot_chat_visible","false"),(0,d.DI)(e,{method:"PUT",body:t})}}toggleRepoCustomInstructions(e){this.dispatch({type:"TOGGLE_REPO_CUSTOM_INSTRUCTIONS",value:e}),_.Jt.setRepoCustomInstructionsState(e)}viewAllThreads(){this.dispatch({type:"VIEW_ALL_THREADS"})}viewCurrentThread(){this.dispatch({type:"VIEW_CURRENT_THREAD"})}maxMessagesReached(){return this.getChatState().messages.length>=3e3}setUsePlanningIntent(e){this.dispatch({type:"SET_USE_PLANNING_INTENT",value:e})}async sendChatMessage({thread:e,content:t,references:s,topic:r,context:a,confirmations:i,customInstructions:n,model:o,customCopilotId:l,intent:d,tools:c,clientToolResults:h,parentMessageId:p,modeOverride:g,skillOptions:m}){let E=(0,u.P)(r),f=E?void 0:r,_=e,S=this.getPendingThreadId(l);if(!_&&l&&S&&(_=this.getThreadById(S),this.removePendingThreadId(l)),E&&!s.some(e=>"docset"===e.type&&e.name===r.name)&&s.push({type:"docset",name:r.name,id:r.id,avatarUrl:r.avatarUrl,repos:r.repos,description:r.description}),!_){let e=(0,u.Y6)({role:"user",content:t,mediaContent:[],references:s});this.dispatch({type:"SET_PENDING_FIRST_MESSAGE",message:e});try{_=await this.createThread({customCopilotId:l})}catch(s){let e="An unexpected error has occurred.";s instanceof Error&&(e=s.message),this.handleSendMessageError(_,x(e),t,"ERROR_THREAD_CREATION",e);return}}let T=s.length?await Promise.all(s.filter(e=>"image"===e.type).map(e=>e.attachment).map(async e=>{if(!e.threadID){e.threadID=_?.id||null;try{await e.prefetch()}catch{let e="An error occurred uploading image attachments";this.handleSendMessageError(_,x(e),t,"ERROR_IMAGE_UPLOAD",e)}}let s=await e.url(),r=e.file;return{mediaType:r.type,name:r.name,url:s,chatAttachmentUrl:s,width:e.width,height:e.height}})):[],y=s.filter(e=>"image"!==e.type);return y=y.filter(e=>"figma"!==e.type||!e.authenticationRequired),null!=_&&this.clearEditedReferencesFromSessionStorage(_.id),this.sendNewMessage(_,t,T,y,d,f,a,i,n,o,l,c,h,p,g,m)}FindLastMessageID(){let e=(0,m.B)(this.getChatState().messages);return e[e.length-1]?.id||"root"}async retryLastUnsuccessfulChatMessage(e){let{currentTopic:t,context:s,customInstructions:r,model:a}=this.getChatState(),i=(0,u.P)(t)?void 0:t,n=(0,m.B)(this.getChatState().messages).findLast(e=>"user"===e.role);if(!n?.content)return;let o=n.references?.length?n.references:e.currentReferences??[],l=n.mediaContent||[];this.dispatch({type:"MESSAGES_CLEAR_LAST_ERROR"}),this.unselectPreviousChildMessage(n);let d="";if(n.clientSide){let e=(0,m.B)(this.getChatState().messages).findLast(e=>!e.clientSide);d=e?"user"===e.role?e.parentMessageID||"root":e.id:"root"}else d=n.id;return this.sendMessage(e,n.content,l,o,n.intent,s,i,r,a,void 0,d)}async retryUserChatMessage(e,t,s){let r,{currentTopic:a,context:i,customInstructions:n,model:o}=this.getChatState(),l=(0,u.P)(a)?void 0:a;if(t.parentMessageID&&(r=this.getChatState().messages.findLast(e=>e.id===t.parentMessageID)),!r||!r.content)return;this.unselectPreviousChildMessage(r);let d=r.references||[],c=r.mediaContent||[];return this.sendMessage(e,r.content,c,d,t.intent,i,l,n,s||o,void 0,r.id)}async editUserChatMessage(e,t,s){if(!s)return;let{currentTopic:r,context:a,customInstructions:i,messages:n,model:o}=this.getChatState(),l=(0,u.P)(r)?void 0:r,d=(0,m.CX)(n,t);if(!d)return;let c=d?.id||"",h=t.clientConfirmations??[],p=t.references||[],g=t.mediaContent||[],E=(0,u.Y6)({role:"user",content:s,mediaContent:g,references:p,thread:e,confirmationResponses:h,parentMessageID:c}),f=(0,u.lG)(l,p);if(this.dispatch({type:"MESSAGE_ADDED",message:E,repoHasCustomInstructions:!!f,usedRepoCustomInstructions:!!(f&&this.repoInstructionsEnabled()),customInstructionsOwners:(0,u.j$)(p)}),this.reloadingThreadPromise&&(this.dispatch({type:"WAITING_ON_COPILOT",loading:!0}),this.afterThreadReloadCallback=()=>{this.dispatch({type:"MESSAGE_ADDED",message:E,repoHasCustomInstructions:!!f,usedRepoCustomInstructions:!!(f&&this.repoInstructionsEnabled()),customInstructionsOwners:(0,u.j$)(p)})},!await this.reloadingThreadPromise))return;let _=d;for(;_&&_.clientSide;)_=(0,m.CX)(n,_);return this.sendMessage(e,s,g,p,t.intent,a,l,i,o,void 0,_?.id||"")}handleFeedback(e,t){this.dispatch({type:"MESSAGE_FEEDBACK",message:e,feedback:t})}setSelectedMessage(e){this.dispatch({type:"MESSAGES_SET_SELECTED_MESSAGE",message:e})}unselectPreviousChildMessage(e){this.dispatch({type:"MESSAGES_UNSELECT_PREVIOUS_MESSAGE",message:e})}async stopStreaming(){this.streamer?(await this.streamer.stop(),this.streamer=void 0):this.messageAbortController?.abort(),this.dispatch({type:"MESSAGE_STREAMING_STOPPED",timings:this.completeTiming()})}async getSystemPrompt(){let{mode:e}=this.getChatState();return await this.systemPrompt(e)}async createThread(e){let t,{customCopilotId:s,preventThreadSelection:r=!1,scopeId:a}=e||{},i=await this.service.createThread(s,a);if(i.ok)return t=i.payload,_.Jt.migrateNullThreadToNewThread(t.id),this.dispatch({type:"THREAD_CREATED",thread:t,preventThreadSelection:r}),t;throw Error(i.error)}async sendNewMessage(e,t,s,r,a,i,n,o,l,d,c,h,p,g,E,f){let{clientSkillConfirmation:S,mode:T}=this.getChatState();S&&(this.dispatch({type:"CLIENT_SKILL_CONFIRMATION_REQUEST",confirmation:void 0}),this.skillExecutor?.resetExecution());let y=(0,u.Y6)({role:"user",content:t,mediaContent:s,references:r,thread:e,confirmationResponses:o?[o]:[],parentMessageID:g||this.FindLastMessageID(),clientToolResults:p,skillOptions:f}),I=(0,u.lG)(i,r);if(this.dispatch({type:"MESSAGE_ADDED",message:y,repoHasCustomInstructions:!!I,usedRepoCustomInstructions:!!(I&&this.repoInstructionsEnabled()),customInstructionsOwners:(0,u.j$)(r)}),!e)try{e=await this.createThread({customCopilotId:c})}catch(r){let s="An unexpected error has occurred.";r instanceof Error&&(s=r.message),this.handleSendMessageError(e,x(s),t,"ERROR_THREAD_CREATION",s);return}this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,updatedAt:new Date().toISOString()}}),this.dispatch({type:"CLEAR_CURRENT_REFERENCES",keepTypes:["docset","magic-knowledge-base"]}),d&&"assistive"!==T&&_.Jt.setModel(e.id,d);let R="";if(!g){let e=(0,m.B)(this.getChatState().messages),t=e[e.length-1];if(g=t?t.clientSide?e.findLast(e=>!e.clientSide&&"assistant"===e.role)?.id||"root":t.id:"root",this.reloadingThreadPromise&&(this.dispatch({type:"WAITING_ON_COPILOT",loading:!0}),this.afterThreadReloadCallback=e=>{0!==e.length&&(y.parentMessageID=R=e[e.length-1].id,this.dispatch({type:"MESSAGE_ADDED",message:y,repoHasCustomInstructions:!!I,usedRepoCustomInstructions:!!(I&&this.repoInstructionsEnabled()),customInstructionsOwners:(0,u.j$)(r)}))},!await this.reloadingThreadPromise))return}return this.sendMessage(e,t,s,r,a,n,i,l,d,o,R||g,h,p,E,f)}async sendMessage(e,t,s,r,a,i,l,d,c,h,g,m=[],f,_,S){let T;a??(a=this.getChatState().usePlanningIntent?E.wh.planningAgent:E.wh.conversation);let y=(0,u.Y6)({role:"assistant",content:"",mediaContent:[],thread:e,parentMessageID:g});y.messageIndex=-1,this.dispatch({type:"WAITING_ON_COPILOT",loading:!0});let R=r.length&&(1!==r.length||r[0]?.type!=="repository")?void 0:i;(0,o.BI)("copilot.implicit_context",{usedImplicitContext:!!R,type:R?.[0]?.type,count:R?.length}),!r.length&&l&&(r=[(0,u.qS)(l)]);let C=[];if(this.repoInstructionsEnabled()){let e=(0,u.NJ)(r);C.push(...e)}d?.type!=="Organization"||C.find(e=>"Organization"===e.type)||C.push(d),d?.type==="Assistant"&&C.push(d);let A=C.find(e=>"Organization"===e.type);A&&r.push((0,u.lj)(A.owner));let w=C.map(e=>e.prompt),{mode:D}=this.getChatState();this.timings={startTime:Date.now()},this.streamer=void 0,this.messageAbortController=new AbortController;let M=[...m,...(T=window.location.pathname,Object.keys(v).reduce((e,t)=>{let s=v[t];if(!s||s.featureFlag&&!(0,I.G7)(s.featureFlag))return e;if("excludePaths"in s){if(s.excludePaths.some(e=>e.test(T)))return e}else if(!("includePaths"in s))return e;else if(!s.includePaths.some(e=>e.test(T)))return e;return e.push(s.schema),e},[]))];try{let i={threadID:e.id,messageID:y.id,content:t,mediaContent:s,intent:a,mode:_||D,references:r,context:R??[],confirmations:h?[h]:[],customInstructions:w,model:c?.id,customCopilotID:(0,n.O)(e),parentMessageID:g,tools:M,clientToolResults:f,signal:this.messageAbortController.signal,skillOptions:S},o=this.activePlugin?.overrideCreateMessageOptions?await this.activePlugin.overrideCreateMessageOptions(i):i,l=await this.service.createMessageStreaming(o);if(l.ok){let s=l.response.body?.getReader();if(!s)return void this.handleSendMessageError(e,x(u.DW),t,"ERROR_STREAM_READER",u.DW);y.requestID=l.response.headers.get("x-github-request-id")||void 0;let r=new p.X(s);this.streamer=r,this.dispatch({type:"MESSAGE_STREAMING_STARTED",message:y}),await this.handleStreamingMessage(e,r)}else{if(this.messageAbortController.signal.aborted)return;this.handleSendMessageError(e,x(l.error),t,"ERROR_MESSAGE_STREAMING",l.error)}}finally{this.streamer=void 0,this.messageAbortController=void 0}}repoInstructionsEnabled(){return!!_.Jt.getRepoCustomInstructionsState()}async populateReferenceLanguage(e){let t=await this.service.fetchLanguageForFileReference(e);if(t.ok&&t.payload.language){let{languageName:s,languageId:r}=t.payload.language;this.replaceReference(e,{...e,languageName:s,languageId:r})}}clearEditedReferencesFromSessionStorage(e){f.W.copilotPersistEditedDraftIssues&&(0,l.zB)(`edited-${e}-`)}addReference(e,t){this.dispatch({type:"ADD_REFERENCE",reference:e,source:t}),(0,u.SI)(e)&&(void 0===e.languageId||void 0===e.languageName)&&this.populateReferenceLanguage(e)}removeReference(e){e&&(G([e]),this.dispatch({type:"REMOVE_REFERENCES",references:[e]}))}removeReferences(e){G(e),this.dispatch({type:"REMOVE_REFERENCES",references:e})}replaceReference(e,t){this.dispatch({type:"REPLACE_REFERENCE",referenceToDelete:e,referenceToInsert:t})}setImageAttachmentUploaded(e,t){this.dispatch({type:"IMAGE_UPLOADED",referenceId:e,dotcomAttachment:t})}selectModel(e,t=!0){this.dispatch({type:"SELECT_MODEL",model:e}),t&&_.Jt.setModel(this.getChatState().selectedThreadID,e)}get activePlugin(){return(0,c.BW)(location,this.plugins)}setCopilotSettings(e){_.Jt.settings=e}async dismissAttachKnowledgeBaseHerePopover(){this.dispatch({type:"DISMISS_ATTACH_KNOWLEDGE_BASE_HERE_POPOVER"}),await (0,d.DI)("/settings/dismiss-notice/copilot_for_docs_attach_knowledge_base_here",{method:"POST"})}async dismissKnowledgeBaseAttachedToChatPopover(){this.dispatch({type:"DISMISS_KNOWLEDGE_BASE_ATTACHED_TO_CHAT_POPOVER"}),await (0,d.DI)("/settings/dismiss-notice/copilot_for_docs_knowledge_base_attached_to_chat",{method:"POST"})}async selectThread(e,t){let{clearTopic:s,includeThreads:r=!0}=t??{};await this.fetchModels(),await this.stopStreaming(),this.dispatch({type:"CLEAR_SHARED_THREAD_CHANNEL"}),this.dispatch({type:"SELECT_THREAD",thread:e,clearTopic:s});let a=[];a.push(this.fetchMessages(e?.id||null)),r&&a.push(this.fetchThreads()),await Promise.all(a)}addMessage(e,t,s,r,a,i,n){let o=(0,u.Y6)({role:e,content:s,mediaContent:r,references:a,thread:t,confirmationResponses:i,clientSkillConfirmations:n,parentMessageID:this.FindLastMessageID()});this.dispatch({type:"MESSAGE_ADDED",message:o})}async renameThread(e,t){(await this.service.renameThread(e.id,t)).ok&&this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,name:t}})}dismissAmbientError(){this.dispatch({type:"DISMISS_AMBIENT_ERROR"})}addAmbientError(e){this.dispatch({type:"ADD_AMBIENT_ERROR",message:e});let{mode:t}=this.getChatState();(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_AMBIENT",mode:t,message:e})}async clearThread(e){(await this.service.clearThread(e.id)).ok&&this.dispatch({type:"CLEAR_THREAD",threadID:e.id})}async deleteThreadKeepSelection(e){this.dispatch({type:"DELETE_THREAD_KEEP_SELECTION",thread:e});let t=await this.service.deleteThread(e.id);t.ok||this.dispatch({type:"DELETE_THREAD_ERROR",thread:e,error:t.error})}async deleteAllThreadKeepSelection(e){this.dispatch({type:"DELETE_ALL_THREADS_KEEP_SELECTION",threads:e});let t=e.map(e=>e.id);for(let s=0;s!0){return Array.from(e.values()).filter(e=>t(e)&&!e.scopeID).sort((e,t)=>new Date(t.updatedAt).getTime()-new Date(e.updatedAt).getTime())}async sendMessageToNewThread(e,t,s,r,a){if(""===t.trim()){let[e,r]=this.tryInferMessage(s);if(!e||!r)return;t=r}e&&(_.Jt.setSavedMessageFast(e,null),_.Jt.clearCurrentReferences(e)),await this.sendNewMessage(null,t,[],s,void 0,void 0,r,void 0,void 0,a)}startThreadReload(){this.reloadingThreadPromise=new Promise(e=>{this.resolvePromise=e})}cancelThreadReload(){this.resolvePromise(!1),this.resolvePromise=()=>{},this.reloadingThreadPromise=void 0,this.afterThreadReloadCallback=void 0,this.fetchingThreadID=null}async fetchMessages(e,t=!1,s=!1){let r=_.Jt.getCurrentReferences(e);if(!e)return this.threadDataLoaded(e,[],r||[]),()=>{};t||this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let a=this.getChatState().messages;this.fetchingThreadID=e;let i=async s=>{let n=await this.service.listMessages(e);if(t&&this.fetchingThreadID!==e)return!1;if(!n.ok)return this.setMessageUpdatedError(n.status,n.payload?.missingOrgIds),this.afterThreadReloadCallback=void 0,!1;if(s&&n.payload.messages.length===a.length)return i(!1);{let t=n.payload.thread;return this.threadDataLoaded(e,n.payload.messages,r||t.currentReferences||[]),this.afterThreadReloadCallback&&(this.afterThreadReloadCallback(n.payload.messages),this.afterThreadReloadCallback=void 0),!0}},n=await i(s);return()=>{this.resolvePromise(n),this.resolvePromise=()=>{},this.reloadingThreadPromise=void 0}}async fetchSharedThreadMessages(e){if(!e)return;this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let t=await this.service.listSharedThreadMessages(e);if(this.dispatch({type:"FETCH_SHARED_THREAD_MESSAGES",ok:t.ok,status:t.status,shareId:e,originalThreadId:t.ok?t.payload.thread.id:void 0}),t.ok){this.threadDataLoaded(e,t.payload.messages,[]),await this.fetchModels();let s=t.payload.messages?.at(-1)?.model,r=s&&this.getChatState().availableModels?.find(e=>e.id===s);r&&this.selectModel(r)}else this.setMessageUpdatedError(t.status,t.payload?.missingOrgIds)}setMessageUpdatedError(e,t){this.dispatch({type:"MESSAGES_UPDATED",state:"error",...404===e?{notFound:!0,missingOrgIds:t}:{}})}selectReference(e){this.dispatch({type:"SELECT_REFERENCE",reference:e})}setTopRepositoryTopics(e){this.dispatch({type:"SET_TOP_REPOSITORIES",topics:e})}async handleStreamingMessage(e,t){try{for await(let s of t.stream())await this.processStreamingMessage(e,s)}catch(s){let t;if(this.isWrappedStreamingResponseError(s))t=this.getStreamingErrorMessage(s.error);else{t=x(u.DW);let{mode:e}=this.getChatState();(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_STREAMING_GENERIC",mode:e,message:"An unexpected error occurred during message streaming."})}this.handleSendMessageError(e,t);return}}isWrappedStreamingResponseError(e){return!!e&&"object"==typeof e&&"error"in e&&!!e.error&&"object"==typeof e.error&&"errorType"in e.error&&"string"==typeof e.error.errorType&&E.C6.includes(e.error.errorType)}async processStreamingMessage(e,t){var s,r,a;switch((s=this.timings).firstByte??(s.firstByte=Date.now()),t.type){case"content":(r=this.timings).firstToken??(r.firstToken=Date.now()),this.dispatch({type:"MESSAGE_STREAMING_TOKEN_ADDED",token:t.body});break;case"functionCall":a=t.name,E.xP.includes(a)&&this.dispatch({type:"MESSAGE_STREAMING_FUNCTION_CALLED",name:t.name,status:t.status,arguments:t.arguments,errorMessage:t.errorMessage,references:t.references,statusMessage:t.statusMessage});break;case"clientSkillsRequest":if(f.W.dotcomChatClientSideSkills){let e=this.getChatState(),s=(0,T.W)(e);this.skillExecutor=new SkillExecutor(s,t.toolCalls,e=>void this.sendChatMessage(e),e,this.dispatch),this.dispatch({type:"CLIENT_SKILLS_REQUEST",toolCalls:t.toolCalls})}break;case"confirmation":this.dispatch({type:"MESSAGE_STREAMING_CONFIRMATION",title:t.title,message:t.message,confirmation:t.confirmation});break;case"threadTitle":this.dispatch({type:"THREAD_UPDATED",thread:{...e,name:t.title}});break;case"complete":t.references=(0,S.q)(t.references),this.dispatch({type:"MESSAGE_STREAMING_COMPLETED",messageResponse:t,timings:this.completeTiming()}),this.handleSendMessageSuccess(e),f.W.dotcomChatClientSideSkills&&(this.skillExecutor?.setParentMessageId(t.id),await this.skillExecutor?.run());break;case"error":{let s=this.getStreamingErrorMessage(t);this.handleSendMessageError(e,s);break}case"debug":console.log("Prompt Body:",t.body);break;case"trace":{let s=this.getChatState().streamingMessage?.createdAt;try{if(!t.traceId){console.error("Received trace data without trace ID from backend, ignoring trace");break}let r=(0,M.r)(t.spans);if(r[0]){let a=s||t.traceId;this.traceDispatch?.({type:"SET_TRACE_INFO",traceInfo:{spanNode:r[0],messageId:a,threadId:e.id,actualTraceId:t.traceId}})}}catch(e){console.error("Failed to process trace info:",e)}break}case"agentError":this.dispatch({type:"AGENT_ERROR",error:{type:t.agentErrorType,code:t.code,message:t.message,identifier:t.identifier}})}}getStreamingErrorMessage(e){let{mode:t}=this.getChatState();switch(e.errorType){case"publicCode":{let e="https://docs.github.com/en/copilot/managing-copilot/managing-copilot-as-an-individual-subscriber/managing-copilot-policies-as-an-individual-subscriber",s=(0,i.jsxs)(i.Fragment,{children:["This response cannot be shown because it references public code, which is restricted by"," ",(0,i.jsx)("a",{href:e,children:"your Copilot settings"}),"."]});return this.hasCEorCBAccess&&(e="https://docs.github.com/en/enterprise-cloud@latest/copilot/managing-copilot/managing-github-copilot-in-your-organization/managing-policies-for-copilot-in-your-organization",s=(0,i.jsxs)(i.Fragment,{children:["This response cannot be shown because it references public code, which is restricted by"," ",(0,i.jsx)("a",{href:e,children:"your organization's Copilot settings"}),"."]})),(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_PUBLIC_CODE",mode:t,message:"This response cannot be shown because it references public code, which is restricted by your Copilot settings."}),{type:"publicCode",isError:!0,message:s,retryable:!0}}case"filtered":{let e=(0,i.jsxs)(i.Fragment,{children:["This response has been filtered because it violates ",(0,i.jsx)("a",{href:"https://docs.github.com/en/site-policy/github-terms/github-terms-for-additional-products-and-features#github-copilot",children:"GitHub's safety policies"}),"."]});return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_FILTERED_RESPONSE",mode:t,message:"This response has been filtered because it violates GitHub's safety policies."}),{type:"filtered",isError:!0,message:e,retryable:!1}}case"contentTooLarge":return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_CONTENT_TOO_LARGE",mode:t,message:u.nN[413]||u.DW}),{isError:!0,message:u.nN[413]||u.DW,type:"basic",retryable:!1};case"rateLimit":return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_RATE_LIMIT",mode:t,message:u.nN[429]||u.DW}),x(u.nN[429]||u.DW);case"agentUnauthorized":{let s=JSON.parse(e.description),r=`You haven't authorized ${s.name} to access your account. You can do that by going here: ${window.location.origin}/login/oauth/authorize?client_id=${s.client_id}`;return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_AGENT_UNAUTHORIZED",mode:t,message:r}),{type:"agentUnauthorized",isError:!0,message:r,details:s}}case"agentRequest":{let s=JSON.parse(e.description);return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_AGENT_REQUEST",mode:t,message:s.message}),{type:"agentRequest",isError:!0,message:s.message,details:s}}case"multipleAgentsAttempt":return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_MULTIPLE_AGENTS_ATTEMPT",mode:t,message:b}),x(b);case"networkError":return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_NETWORK",mode:t,message:u.nN[408]||u.DW}),x(u.nN[408]||u.DW);default:return(0,o.BI)("dotcom_chat.activate.error",{target:"ERROR_EXCEPTION",mode:t,message:u.FF[e.errorType]||u.DW}),x(u.FF[e.errorType]||u.DW)}}handleSendMessageSuccess(e){_.Jt.setSavedMessageFast(e.id,null),_.Jt.clearCurrentReferences(e.id),this.dispatch({type:"WAITING_ON_COPILOT",loading:!1})}handleSendMessageError(e,t,s,r,a=u.DW){e&&s&&_.Jt.setSavedUserMessageOnError(e.id,s);let i=(0,m.B)(this.getChatState().messages).findLast(e=>"user"===e.role)?.id||"root",n=(0,u.Y6)({role:"assistant",content:"",mediaContent:[],error:t,thread:e,parentMessageID:i});if(this.dispatch({type:"MESSAGE_ADDED",message:n}),this.dispatch({type:"WAITING_ON_COPILOT",loading:!1}),this.dispatch({type:"MESSAGE_STREAMING_FAILED",timings:this.completeTiming()}),r){let{mode:e}=this.getChatState();(0,o.BI)("dotcom_chat.activate.error",{target:r,mode:e,message:a})}}async fetchModels(){if(N){let{availableModels:e}=this.getChatState();(!e||N.length>e.length)&&this.dispatch({type:"MODELS_LOADED",models:N});return}this.dispatch({type:"MODELS_LOADING"});let e=await this.service.listModels();if(e.ok){let t=(0,y.eW)(e.payload);N=t,this.dispatch({type:"MODELS_LOADED",models:t});let s=_.Jt.getModel(this.getChatState().selectedThreadID)?.id,r=t.find(e=>e.id===s)||t.find(e=>e.is_chat_default);r&&this.dispatch({type:"SELECT_MODEL",model:r})}else this.dispatch({type:"MODELS_LOADING_ERROR",error:e.error})}async acceptModelPolicy(e){e.policy&&"enabled"!==e.policy.state&&(await this.service.setModelPolicyState(e.id,"enabled"),N=null,this.fetchModels())}async fetchThreads(){this.dispatch({type:"THREADS_LOADING"});let e=await this.service.fetchThreads();return e.ok?(setTimeout(()=>this.dispatch({type:"THREADS_LOADED",threads:e.payload}),100),e.payload):(setTimeout(()=>this.dispatch({type:"THREADS_LOADING_ERROR",message:e.error,status:e.status}),100),null)}async fetchSharedThreads(){this.dispatch({type:"SHARED_THREADS_LOADING"});let e=await this.service.fetchSharedThreads();return e.ok?(setTimeout(()=>this.dispatch({type:"SHARED_THREADS_LOADED"}),100),e.payload):(setTimeout(()=>this.dispatch({type:"SHARED_THREADS_LOADING_ERROR",message:e.error}),100),null)}async fetchLatestThread(e){let t=await this.service.fetchLatestThread(e);return t.ok?(t.payload&&this.dispatch({type:"LATEST_THREAD_LOADED",latestThread:t.payload}),t.payload):null}async continueSharedThread(e){if(!e)return this.dispatch({type:"THREAD_CONTINUED_FAILED"}),null;this.dispatch({type:"MESSAGES_UPDATED",state:"loading"});let t=await this.service.continueSharedThread(e);if(!t.ok)return null;{let{thread:e,messages:s}=t.payload;this.dispatch({type:"THREAD_CONTINUED",thread:e}),this.dispatch({type:"MESSAGES_UPDATED",state:"loaded",messages:s})}return t.payload}async unshareAllThreads(){let e=await this.service.unshareAllThreads();if(!e.ok)return this.dispatch({type:"ADD_AMBIENT_ERROR",message:e.error||"Failed to unshare all threads"}),e;for(let e of Array.from(this.getChatState().threads.values()))e.sharedAt&&this.dispatch({type:"THREAD_UPDATED",thread:{id:e.id,sharedAt:void 0,sharedID:void 0}});return e}async findOrStartNewThread(e,t){let s=null;if(e)s=e;else{let e=_.Jt.selectedThreadID||void 0;s=await this.fetchLatestThread(e)}if(s&&((0,u.F2)(s)||s.customCopilotID)&&(s=null),s&&t){let e=await this.service.listMessages(s.id);if(e.ok){let r=e.payload.messages,a=r?.length;a>=2&&!r[a-2]?.references?.find(e=>(0,u.x_)(e,t))&&(s=null)}}return await this.selectThread(s,{includeThreads:!1}),s}async systemPrompt(e){let t=await this.service.getSystemPrompt(e);return t.ok?t.payload.prompt:""}async fetchAgents(e){let t=await this.service.listAgents(e),s=[];return t.ok&&(s=t.payload,this.dispatch({type:"SET_AGENTS",agents:s})),s}async fetchCopilotSpace(e){let t=await this.service.fetchCopilotSpace(e),s={};return t.ok&&(s=t.payload),s}async fetchCurrentRepo(e){let t=await this.service.fetchRepo(e);if(t.ok)return this.dispatch({type:"ADD_REFERENCE",reference:(0,u.qS)(t.payload),source:"currentRepo"}),t.payload}async fetchKnowledgeBases(){this.dispatch({type:"KNOWLEDGE_BASES_LOADING"});let e=await this.service.listDocsets();return e.ok?this.dispatch({type:"KNOWLEDGE_BASES_LOADED",knowledgeBases:e.payload}):this.dispatch({type:"KNOWLEDGE_BASES_LOADING_ERROR",message:e.error}),e}async fetchImplicitContext(e,t,s){let r=await this.service.fetchImplicitContext(e,t,s);if(r.ok){let e=r.payload?Array.isArray(r.payload)?r.payload:[r.payload]:void 0;this.dispatch({type:"IMPLICIT_CONTEXT_UPDATED",context:e}),e&&e.length>0&&void 0!==e[0]&&this.generateSuggestions(e[0])}}async deleteDocset(e){return(await this.service.deleteDocset(e)).ok}threadDataLoaded(e,t,s){this.dispatch({type:"MESSAGES_UPDATED",messages:t,state:"loaded"}),this.dispatch({type:"REFERENCES_LOADED",references:s})}dismissEditorUpsellBanner(){let e=new FormData;e.set("copilot_editor_upsell_banner_dismissed","true"),(0,d.DI)("/github-copilot/preferences",{method:"PUT",body:e}),this.dispatch({type:"DISMISS_EDITOR_UPSELL_BANNER"})}tryInferMessage(e){return e&&e.find(e=>"image"===e.type)?[!0,"Describe this image"]:[!1,void 0]}setWrapCodeLines(e){this.dispatch({type:"SET_WRAP_CODE_LINES",value:e}),_.Jt.setWrapCodeLines(e)}clearDefaultRecipient(){this.dispatch({type:"CLEAR_DEFAULT_RECIPIENT"})}completeTiming(){return{...this.timings,endTime:Date.now()}}getCustomCopilotKey(e){return e?`${e.owner}:${e.id}`:"default"}getThreadById(e){return e&&this.getChatState().threads.get(e)||null}getPendingThreadId(e){let t=this.getCustomCopilotKey(e);return this.pendingThreadsByCopilotSpaceId.get(t)||null}setPendingThreadId(e,t){let s=this.getCustomCopilotKey(t);this.pendingThreadsByCopilotSpaceId.set(s,e)}removePendingThreadId(e){let t=this.getCustomCopilotKey(e);this.pendingThreadsByCopilotSpaceId.delete(t)}async selectPendingThread(e){let t=this.getPendingThreadId(e),s=this.getThreadById(t);s&&await this.selectThread(s)}constructor(e,t,s,r,i,n,o,l,d,c){(0,a._)(this,"dispatch",void 0),(0,a._)(this,"traceDispatch",void 0),(0,a._)(this,"service",void 0),(0,a._)(this,"getChatState",void 0),(0,a._)(this,"hasCEorCBAccess",void 0),(0,a._)(this,"timings",{startTime:0}),(0,a._)(this,"skillExecutor",void 0),(0,a._)(this,"streamer",void 0),(0,a._)(this,"messageAbortController",void 0),(0,a._)(this,"reloadingThreadPromise",void 0),(0,a._)(this,"fetchingThreadID",null),(0,a._)(this,"afterThreadReloadCallback",void 0),(0,a._)(this,"pendingThreadsByCopilotSpaceId",new Map),(0,a._)(this,"plugins",void 0),(0,a._)(this,"clearCurrentReferences",e=>{e&&e.includes("image")||G(this.getChatState().currentReferences),this.dispatch({type:"CLEAR_CURRENT_REFERENCES",keepTypes:e})}),(0,a._)(this,"clearAllReferences",()=>{G(this.getChatState().currentReferences),this.dispatch({type:"CLEAR_ALL_REFERENCES"})}),(0,a._)(this,"resolvePromise",()=>{}),(0,a._)(this,"clearCurrentTopic",()=>{this.dispatch({type:"CURRENT_TOPIC_UPDATED",topic:void 0,state:"loaded"})}),(0,a._)(this,"showTopicPicker",(e=!0)=>{this.dispatch({type:"SHOW_TOPIC_PICKER",show:e})}),(0,a._)(this,"startEditingMessage",e=>this.dispatch({type:"START_EDITING_MESSAGE",messageId:e})),(0,a._)(this,"cancelEditingMessage",()=>this.dispatch({type:"CANCEL_EDITING_MESSAGE"})),this.dispatch=e,this.traceDispatch=c,this.service=n??new g.k(t,s,i,d),this.getChatState=r,this.hasCEorCBAccess=!!o,this.plugins=l}};function k(e){var t;return P(e,[E.wh.explain,E.wh.suggest])||P(e,[E.wh.conversation])&&"content"in(t=e)&&"string"==typeof t.content}function P(e,t){return new Set(t).has(e.intent)}function x(e){return{isError:!0,message:e,type:"basic",retryable:!0}}function B(e,t){let s=document.getElementById(e);s?.setAttribute("aria-expanded",t?"true":"false")}function G(e){for(let t of e)if("image"===t.type){let e=t.attachment;e instanceof L.N&&e.abortController.abort("Reference removed before upload completed")}}try{(r=Intent).displayName||(r.displayName="Intent")}catch{}},23657:(e,t,s)=>{s.d(t,{Cb:()=>u,FQ:()=>g,Hh:()=>I,JB:()=>S,Ku:()=>d,Pg:()=>C,UG:()=>_,Ym:()=>f,fn:()=>T,iI:()=>E,j0:()=>l,mM:()=>m,q5:()=>R,rl:()=>y,y_:()=>p});var r=s(53419),a=s(25407),i=s(88934),n=s(96540),o=s(25641);let l="The name of this space is too close to another existing space. Please modify the name and try again.",d="https://github.com/mcp/github/github-mcp-server",c="[a-zA-Z0-9-_]+",h="[0-9]+";function u(e){let{id:t,owner:s}=e;return`${o.VR}/${s}/${t}`}function p(){let e=(0,i.zy)().pathname;return(0,n.useMemo)(()=>e===o.VR||e===`${o.VR}/`,[e])}function g(e=!1){let t=(0,i.zy)().pathname;return(0,n.useMemo)(()=>(function(e,t=!1){let s=`${o.VR}/${c}/${h}`,r=RegExp(`^${s}${t?"(/edit)?":""}$`);return!!e.match(r)})(t,e),[e,t])}function m(){let e=p(),t=g();return e||t}function E(){let e=(0,i.zy)().pathname;return(0,n.useMemo)(()=>{let t=e.match(RegExp(`${o.VR}/(${c})/(${h})`));if(t){let[,e,s]=t;if(e&&s){let t=parseInt(s,10);if(!isNaN(t))return{id:t,owner:e}}}return null},[e])}function f(e,t){return e===t||null!==e&&null!==t&&e.id===t.id&&e.owner===t.owner}function _(e,t){return e.id===t.id&&e.owner===t.owner}function S(e,t){if(t)return e?.find(e=>_(e,t))}function T(e){return e?`${o.VR}/${e.owner}/${e.id}`:o.VR}function y(e,t,s=!1){let r,a=t.indexOf("/");if(-1!==a&&0!==a){let s=t.slice(0,a),i=t.slice(a+1);r=e===s?`org:${e} ${i}`:`org:${s} ${i} visibility:public`}else r=`org:${e} ${t}`;return`${r} in:name archived:false ${s?"fork:true":""}`.trim().replace(/\s+/g," ")}function I(e){return(e?.sizePercentage??0)>100}function R(e){let t=e.filePath.split("/"),s=t.pop(),r=[e.nwo,...t].join("/"),i=e.nwo.split("/"),n=e.sha;return{filePath:r,fileName:s,fileUrl:e.fileExists&&e.sha?(0,a.IO9)({repo:{ownerLogin:i[0],name:i[1]},commitish:e.sha,action:"blob",path:e.filePath}):void 0,sha:n}}function C(e,t){let s={...e.reduce((e,t)=>(e[t.type]=(e[t.type]||0)+1,e),{}),source:t};(0,r.BI)("copilot-spaces.resources-added",s)}},25536:(e,t,s)=>{s.d(t,{M:()=>o,O:()=>l});var r=s(74848),a=s(21728),i=s(96540);let n=(0,i.createContext)(null);function o(e){let t,s,o,l=(0,a.c)(7),{selectedThreadId:d,children:c}=e,[h,u]=(0,i.useState)();l[0]===Symbol.for("react.memo_cache_sentinel")?(t=e=>{u(e)},l[0]=t):t=l[0];let p=t;l[1]!==h||l[2]!==d?(s={selectedCopilotSpaceId:h,setSelectedCopilotSpaceId:p,selectedThreadId:d},l[1]=h,l[2]=d,l[3]=s):s=l[3];let g=s;return l[4]!==c||l[5]!==g?(o=(0,r.jsx)(n.Provider,{value:g,children:c}),l[4]=c,l[5]=g,l[6]=o):o=l[6],o}function l(){let e=(0,i.useContext)(n);if(!e)throw Error("useCopilotSpaceSelection must be used within a CopilotSpaceSelectionProvider");return e}try{n.displayName||(n.displayName="CopilotSpaceSelectionContext")}catch{}try{o.displayName||(o.displayName="CopilotSpaceSelectionProvider")}catch{}},26239:(e,t,s)=>{s.d(t,{Bc:()=>i,Qs:()=>d,fv:()=>n,uN:()=>a,wJ:()=>l,wX:()=>o,wg:()=>r});let r="copilot-chat-textarea",a="copilot-chat-topic-search",i="Review",n="copilot-chat-header-button",o="copilot-diff-header-button",l="copilot-chat-panel",d="copilot-chat-panel"},30456:(e,t,s)=>{s.d(t,{N:()=>UploadableFileAttachment});var r=s(35750),a=s(18150),i=s(85242),n=s(50467),o=s(6219),l=s(34681);async function d(e,t){return void 0!==t.width&&void 0!==t.height?{width:t.width,height:t.height}:e.type.startsWith("image/")?new Promise((s,r)=>{let a=new FileReader;a.onload=e=>{if(!e.target?.result||"string"!=typeof e.target.result)return void s({width:void 0,height:void 0});let a=new Image;a.onload=()=>{t.width=a.width,t.height=a.height,s({width:a.width,height:a.height})},a.onerror=()=>r(Error("Failed to load image for dimension extraction")),a.src=e.target.result},a.readAsDataURL(e)}):{width:void 0,height:void 0}}var c=new WeakMap,h=new WeakMap,u=new WeakMap;let UploadableFileAttachment=class UploadableFileAttachment{prefetch(){return(0,r._)(this,u).load()}get previewUrl(){return(0,r._)(this,u).read().href}async url(){return(await (0,r._)(this,u).load()).href}async getDimensions(){return d(this.file,this)}constructor(e,t,s=null){(0,n._)(this,"file",void 0),(0,n._)(this,"width",void 0),(0,n._)(this,"height",void 0),(0,a._)(this,c,{writable:!0,value:void 0}),(0,a._)(this,h,{writable:!0,value:void 0}),(0,n._)(this,"abortController",void 0),(0,n._)(this,"key",void 0),(0,n._)(this,"threadID",void 0),(0,n._)(this,"isLoaded",!1),(0,n._)(this,"hasError",!1),(0,a._)(this,u,{writable:!0,value:(0,l.Z)(async()=>{let e=await (0,o.BV)({name:this.file.name,size:String(this.file.size),content_type:this.file.type,thread_id:this.threadID},"/upload/policies/copilot-chat-attachments",(0,r._)(this,h));await (0,o.QM)(this.file,e,(0,r._)(this,h));let t=await (0,o.My)(e,(0,r._)(this,h)),s=await (0,r._)(this,c);return this.width=s.width,this.height=s.height,this.isLoaded=!0,t})}),this.file=t,this.abortController=new AbortController,(0,i._)(this,h,this.abortController.signal),this.key=e,(0,i._)(this,c,this.getDimensions()),this.threadID=s}}},33592:(e,t,s)=>{s.d(t,{b:()=>g,v:()=>p});var r=s(74848),a=s(21728),i=s(70170),n=s(96540),o=s(79184),l=s(37294),d=s(47789),c=s(16946),h=s(72206);let u=(0,n.createContext)(null);function p(e){let t,s,p,g,m=(0,a.c)(20),{apiURL:E,state:f,dispatch:_,ssoOrganizations:S,children:T,realIp:y,hasCEorCBAccess:I,apiVersion:R}=e,C=(0,h.tD)(),A=(0,d.qw)(),w=(0,l.jR)();m[0]!==E||m[1]!==R||m[2]!==_||m[3]!==C||m[4]!==I||m[5]!==A||m[6]!==y||m[7]!==S||m[8]!==w?(t=new c.e8(_,E,S,C,y,void 0,I,A,R,w),m[0]=E,m[1]=R,m[2]=_,m[3]=C,m[4]=I,m[5]=A,m[6]=y,m[7]=S,m[8]=w,m[9]=t):t=m[9];let D=t,{licenseType:v}=(0,o.xR)();return m[10]!==D||m[11]!==f.chatIsOpen?(s=()=>{let e=new AbortController,t=async()=>{let e=window.location.hash,t=window.location.pathname,s=window.location.hash?`${t}${e}`:t,r=s.slice(1).split("/");if(r.length<2)return;let a=r[0],i=r[1];a&&i&&await D.fetchImplicitContext(s,a,i)},s=(0,i.s)(()=>{t()},500);if(f.chatIsOpen){s();let{replaceState:t,pushState:r}=window.history;window.history.replaceState=function(...e){t.apply(window.history,e),D.clearSuggestions(),window.dispatchEvent(new Event("replaceState"))},window.history.pushState=function(...e){r.apply(window.history,e),D.clearSuggestions(),window.dispatchEvent(new Event("pushState"))},window.addEventListener("popstate",s,{signal:e.signal}),window.addEventListener("replaceState",s,{signal:e.signal}),window.addEventListener("pushState",s,{signal:e.signal})}return()=>{e.abort()}},m[10]=D,m[11]=f.chatIsOpen,m[12]=s):s=m[12],m[13]!==v||m[14]!==D||m[15]!==f.chatIsOpen?(p=[D,f.chatIsOpen,v],m[13]=v,m[14]=D,m[15]=f.chatIsOpen,m[16]=p):p=m[16],(0,n.useEffect)(s,p),m[17]!==T||m[18]!==D?(g=(0,r.jsx)(u.Provider,{value:D,children:T}),m[17]=T,m[18]=D,m[19]=g):g=m[19],g}function g(){let e=(0,n.useContext)(u);if(!e)throw Error("useChatManager must be used within a CopilotChatManagerProvider");return e}try{u.displayName||(u.displayName="CopilotChatManagerContext")}catch{}try{p.displayName||(p.displayName="CopilotChatManagerProvider")}catch{}},34681:(e,t,s)=>{s.d(t,{Z:()=>r});function r(e){let t,s=null;return{load:()=>(s||(s=e().then(e=>t=e)),s),read(){if(t)return t;throw this.load()}}}},38627:(e,t,s)=>{function r(e,t){if(e?.components)return e.components.find(e=>e.routes.some(e=>e instanceof RegExp?e.test(t.pathname):e(t)))}function a(e,t){let{pathname:s}=e;if(!s)return;let r={pathname:s,search:e.search||"",hash:e.hash||""};return t.find(e=>{var t,s;return!!e.components&&e.components.length>0&&(t=e,s=r,!!t.components&&t.components.length>0&&t.components.some(e=>e.routes.some(e=>e instanceof RegExp?e.test(s.pathname):e(s))))})}s.d(t,{BW:()=>a,bG:()=>r})},39689:(e,t,s)=>{s.d(t,{K:()=>ReadLocalWorkspaceFileSkill});var r=s(50467),a=s(82075),i=s(62154),n=s(90254);let ReadLocalWorkspaceFileSkill=class ReadLocalWorkspaceFileSkill{requiresConfirmation(){return!1}confirmationMessage(){return"Read the local workspace file"}static schema(){return{type:"function",function:{name:"read-local-workspace-file",description:"Read a local file. This can be used to read files on the user's local machine. It is the equivalent of running `cat` in the terminal. The file path is relative to the current directory.",parameters:{type:"object",required:["path","repository","pullRequest"],properties:{path:{type:"string",description:"The path to the file to read."},repository:{required:["ownerLogin","name"],type:"object",description:"the repository containing the file to read.",properties:{ownerLogin:{type:"string",description:"the owner of the repository."},name:{type:"string",description:"the name of the repository."}}},pullRequest:{type:"object",description:"the pull request containing the file to read.",required:["number","headSHA"],properties:{number:{type:"string",description:"the number of the pull request."},headSHA:{type:"string",description:"the head SHA of the pull request."}}}}}}}}assertDefined(e,t){if(null==e)throw Error(t)}validateArgs(){let e=JSON.parse(this.rawArguments);return this.assertDefined(e,"No parsed arguments found in raw arguments"),this.assertDefined(e.path,"No path found on parsed arguments"),this.assertDefined(e.repository,"No repository found on parsed arguments"),this.assertDefined(e.pullRequest,"No pullRequest found on parsed arguments"),this.assertDefined(e.repository.ownerLogin,"No ownerLogin found on repository"),this.assertDefined(e.repository.name,"No name found on repository"),this.assertDefined(e.pullRequest.number,"No number found on pullRequest"),this.assertDefined(e.pullRequest.headSHA,"No headSHA found on pullRequest"),e}getArguments(){let e=this.validateArgs(),{repository:t,pullRequest:s}=e;return{path:e.path.startsWith("./")?e.path.slice(2):e.path,repository:t,pullRequest:s}}async fetchBlob(e,t,s){try{let r=await this.blobService.getBlob(e,t.ownerLogin,s.number,t.name,s.headSHA);return r.ok&&r.payload.blobContents||""}catch{return""}}toResult(e,t){return{ok:t,result:e}}async execute(){try{let e=(0,a.A)("localStorage"),{path:t,repository:s,pullRequest:r}=this.getArguments(),i=await this.fetchBlob(t,s,r),o=`hadron-editor-file-deltas-v2/${s.ownerLogin}/${s.name}/${r.number}`,l=JSON.parse(e.getItem(o)||"{}"),d=(l||{diffs:[],sessionId:"",latestTimestamp:0}).diffs?.find(e=>e.path===t);if(!d)return this.toResult(i,!0);let c=i?(0,n.X6)(i,d.diff):(0,n.Gu)(d.diff),h=!1===c?i:c;return this.toResult(h,!0)}catch(t){let e=`Error: ${t instanceof Error?t.message:`Error executing ${this.name} skill`}`;return this.toResult(e,!1)}}constructor(e,t,s){(0,r._)(this,"id",void 0),(0,r._)(this,"name",void 0),(0,r._)(this,"rawArguments",void 0),(0,r._)(this,"blobService",void 0),this.id=e,this.name=t,this.rawArguments=s,this.blobService=new i.T}}},40104:(e,t,s)=>{s.d(t,{D6:()=>h,Fo:()=>d,MV:()=>u,zB:()=>p});var r=s(50467),a=s(82075),i=s(96540);let n=(0,a.A)("sessionStorage"),o="session-storage-update",l=class UseSessionStorageUpdateEvent extends Event{constructor(e,t){super(o),(0,r._)(this,"storageKey",void 0),(0,r._)(this,"storageValue",void 0),this.storageKey=e,this.storageValue=t}};function d(e,t){let s=(0,i.useRef)(t);(0,i.useEffect)(()=>{s.current=t});let[r,a]=(0,i.useState)(()=>{let t=n.getItem(e);return t?JSON.parse(t):s.current}),d=(0,i.useCallback)(t=>{a(void 0!==t?t:s.current),void 0===t?n.removeItem(e):n.setItem(e,JSON.stringify(t)),document.dispatchEvent(new l(e,t))},[e]),c=(0,i.useCallback)(e=>{s.current=e},[s]);return(0,i.useEffect)(()=>{function t(t){if(t.storageKey===e){let e=t.storageValue;a(void 0!==e?e:s.current)}}document.addEventListener(o,t);let r=n.getItem(e);return r?a(JSON.parse(r)):a(s.current),()=>{document.removeEventListener(o,t)}},[e]),[r,d,c]}function c(e){let t=n.getKeys(),s=[];for(let r in t)t[r]?.startsWith(e)&&s.push(t[r]);return s}function h(e){for(let t of e)n.removeItem(t),document.dispatchEvent(new l(t,void 0))}function u(e){let t=[];for(let s of c(e)){let e=n.getItem(s);null!=e&&t.push(JSON.parse(e))}return t}function p(e){h(c(e))}},47789:(e,t,s)=>{s.d(t,{Hb:()=>o,qw:()=>l});var r=s(74848),a=s(21728),i=s(96540);let n=(0,i.createContext)([]);function o(e){let t,s=(0,a.c)(3),{plugins:i,children:o}=e;return s[0]!==o||s[1]!==i?(t=(0,r.jsx)(n.Provider,{value:i,children:o}),s[0]=o,s[1]=i,s[2]=t):t=s[2],t}function l(){return(0,i.useContext)(n)}try{n.displayName||(n.displayName="PluginsContext")}catch{}try{o.displayName||(o.displayName="ImmersivePluginsProvider")}catch{}},62154:(e,t,s)=>{s.d(t,{T:()=>BlobService});var r=s(50467),a=s(14457),i=s(25641),n=s(96379),o=s(11053);let BlobService=class BlobService{async fetchBlob(e,t,s,r,a){try{let l=(0,o.WN)({commitOid:a,owner:t,path:e,pullNumber:s,repo:r}),d=await (0,n.Sr)(l,{method:"GET"});if(d.ok){let e=await d.json();return{status:d.status,ok:!0,payload:e}}return{status:d.status,ok:!1,error:i.DW}}catch{return{status:500,ok:!1,error:i.DW}}}async getBlob(e,t,s,r,a){return this.blobCache.get(e,t,s,r,a)}constructor(){(0,r._)(this,"blobCache",new a.d(this.fetchBlob))}}},68074:(e,t,s)=>{s.d(t,{kk:()=>i,mL:()=>l,qm:()=>o,sT:()=>a,t:()=>n});var r=s(53627);let a="open_panel",i="pull_request_review_comment_id",n="initial_path";function o(e){let t=new URL(window.location.href,window.location.origin);t.searchParams.delete(e),(0,r.kd)(t.toString())}function l(e,t,s){let a=new URL(window.location.href,window.location.origin);a.searchParams.set(e,t),s?s(a.searchParams):(0,r.kd)(a.toString())}},72206:(e,t,s)=>{s.d(t,{rE:()=>o,sw:()=>i,tD:()=>n});var r=s(96540);let a=(0,r.createContext)(null),i=a.Provider;function n(){let e=(0,r.useContext)(a);if(!e||!e.current)throw Error("useGetChatState can only be used inside a CopilotChatProvider");return(0,r.useCallback)(()=>e.current.value,[e])}function o(){return(0,r.useContext)(a)}try{a.displayName||(a.displayName="ObservableChatStateContext")}catch{}},72303:(e,t,s)=>{s.d(t,{W:()=>r});function r(e){return e.selectedThreadID&&e.threads.get(e.selectedThreadID)||null}},73017:(e,t,s)=>{s.d(t,{$6:()=>d,JR:()=>o,vb:()=>n});var r=s(74848),a=s(87448),i=s(96540);let n=c(a.az),o=c(a.EY),l=(0,i.forwardRef)((e,t)=>(0,r.jsx)("div",{ref:t,...e}));l.displayName="Div";let d=c(l);function c(e){let t=(0,i.forwardRef)((t,s)=>{let{html:a,...i}=t;return(0,r.jsx)(e,{ref:s,...i,dangerouslySetInnerHTML:a?{__html:a}:void 0})});return t.displayName=`SafeHTML${e.displayName||e.name}`,t}try{n.displayName||(n.displayName="VerifiedHTMLBox")}catch{}try{o.displayName||(o.displayName="VerifiedHTMLText")}catch{}try{d.displayName||(d.displayName="VerifiedHTMLDiv")}catch{}},73952:(e,t,s)=>{s.d(t,{B:()=>i,CX:()=>c,HR:()=>l,TC:()=>o,Y$:()=>d,ws:()=>n,zh:()=>a});var r=s(53419);function a(e,t=!0){let s=performance.now(),i=0,n={id:"root",role:"user",createdAt:"",threadID:"",references:null,childMessageIndexes:[],messageIndex:0,clientSide:!1};if(0===e.length)return e=[n],i=performance.now()-s,(0,r.BI)("copilot.timings",{function:"constructMessagesHierarchy",timeElapsed:i,messagesLength:e.length,selectMostRecentMessages:t}),e;"root"!==e[0].id&&(e=[n,...e],(0,r.BI)("copilot.legacy_thread_updated",{threadID:e[1].threadID,messagesLength:e.length,selectMostRecentMessages:t}));let o=e[1];if(!o)return e;[e,o]=h(e,1,"parentMessageID","root");let l=new Map,d=[];for(let[t,s]of e.entries()){if([e,s]=h(e,t,"messageIndex",t),d[t]=[],l.set(s.id,t),"root"===s.id)continue;s.parentMessageID||([e,s]=h(e,t,"parentMessageID",o.id),o=s);let r=l.get(s.parentMessageID);if(void 0!==r){[e,s]=h(e,t,"parentMessageIndex",r);let a=e[r];a&&(d[r].push(t),void 0===a.selectedChildIndex&&([e,a]=h(e,r,"selectedChildIndex",t)))}}for(let t=0;t({...e})),r=s[t.parentMessageIndex];return r&&(r.selectedChildIndex=t.messageIndex),s}function o(e,t){let s=e.map(e=>({...e})),r=s[t.messageIndex];return r&&void 0!==r.selectedChildIndex&&(r.selectedChildIndex=void 0),s}function l(e,t){let s=e.findIndex(e=>e.id===t?.parentMessageID);if(-1!==s){let r=e[s],a={...t};a.messageIndex=e.length,a.childMessageIndexes=[],a.parentMessageIndex=r.messageIndex;let i=r.childMessageIndexes?.slice()||[];i.includes(a.messageIndex)||i.push(a.messageIndex),r={...r,childMessageIndexes:i,selectedChildIndex:a.messageIndex},e=[...e,a].toSpliced(s,1,r)}return e}function d(e,t){if(null==e.find(e=>e.id===t?.parentMessageID)){let s=i(e),r=s[s.length-1];if(void 0!==r)if(r.clientSide&&"user"===r.role){let s=e.indexOf(r);[e,r]=h(e,s,"id",t.parentMessageID),[e,r]=h(e,s,"clientSide",!1)}else t.parentMessageID=r.id}return e}function c(e,t){return void 0!==t.parentMessageIndex?e[t.parentMessageIndex]:void 0}function h(e,t,s,r){let a=e[t];if(!a)throw Error(`Message at index ${t} does not exist.`);let i=a[s];if(i===r||Array.isArray(i)&&Array.isArray(r)&&i.length===r.length&&i.every((e,t)=>e===r[t]))return[e,a];let n={...a,[s]:r},o=[...e];return o[t]=n,[o,o[t]]}},79802:(e,t,s)=>{s.d(t,{O:()=>r});function r(e){return e&&e.customCopilotID&&e.customCopilotOwner?{id:e.customCopilotID,owner:e.customCopilotOwner}:null}},86339:(e,t,s)=>{s.d(t,{X:()=>CopilotChatMessageStreamer});var r=s(50467);let a=` `,i=/^data:\s+/;let CopilotStreamingError=class CopilotStreamingError extends Error{constructor(e){super(e.description),(0,r._)(this,"error",void 0),this.error=e,this.name="CopilotStreamingError"}};let CopilotChatMessageStreamer=class CopilotChatMessageStreamer{async *stream(){let e=new TextDecoder("utf-8"),t="";for(;;){let s,r;try{({value:s,done:r}=await this.reader.read())}catch{throw new CopilotStreamingError({type:"error",errorType:"networkError",description:"NETWORK_CONNECTION_INTERRUPTED"})}if(r)break;for(t+=e.decode(s);;){let e=t.indexOf(a);if(-1===e)break;let s=t.slice(0,e).replace(i,"");if("[DONE]"===s)return;let r=JSON.parse(s);if(yield r,r?.type==="complete")return;t=t.slice(e+a.length)}}}async stop(){return this.reader.cancel()}constructor(e){(0,r._)(this,"reader",void 0),this.reader=e}}}}]); //# sourceMappingURL=packages_copilot-chat_utils_CopilotChatContext_tsx-packages_safe-html_VerifiedHTML_tsx-16407f65f766.js.map